【发布时间】:2022-01-23 21:46:32
【问题描述】:
所以我有一个像这样名为 Student 的班级:
public class Student {
public int usercounter;
public String username,password,studentname;
Student(String studentname ,String username, String password, int usercounter){
this.studentname = studentname;
this.username = username;
this.password = password;
this.usercounter = usercounter;
}
我正在尝试使用 Arraylists 编写库登录代码。
static ArrayList<Student> users = new ArrayList<Student>();
我的主菜单如下所示:
public static void MainMenu() {
while (menubreak){
System.out.println("ULIS Main Menu\nPlease choose the feature you want to access:\n1-Login\n2-Create User\n3-Delete User\n4-Exit");
gir = Input.nextInt();
Input.nextLine();
switch (gir) {
case 1:
Login();
break;
我创建这样的用户:
public static void CreateUser() {
while (userbreak) {
System.out.println("You are creating a new User");
System.out.println("Please enter the name of the Student:");
tempStudentname = Input.nextLine();
System.out.println("Please enter a new username:");
tempUsername = Input.nextLine();
System.out.println("Please enter a new password:");
tempPassword = Input.nextLine();
users.add(new Student(tempStudentname, tempUsername, tempPassword, usercounter));
usercounter++;
我的登录屏幕如下所示:
public static void Login() {
System.out.println("Please choose the user type you want to login:\n1-Admin\n2-Student");
giris = Input.nextInt(); Input.nextLine();
switch (giris) {
case 2:
System.out.println("Please enter your username:");
tempUsername = Input.nextLine();
searchUsername = tempUsername;
System.out.println("Please enter your password:");
tempPassword = Input.nextLine();
if(users.contains(searchUsername) && users.contains(tempPassword) ){
System.out.println("User found, logging in now");
UserMenu();
}
else{
System.out.println("User cannot be found, returning to Main Menu");
}
}
}
当我运行它时,它会转到“找不到用户” 我不允许使用离线数据库或类似的东西,这就是为什么我在旅途中创建用户名并且不将它们存储在某些东西中的原因。 它找不到它正在寻找的用户名和密码的原因可能是什么?顺便说一句,我是一年级的学生,如果可以的话,请尝试在不使用复杂技术的情况下进行解释
【问题讨论】:
-
您没有向我们展示
users是如何创建或填充的,因此很难为您提供帮助。 (您也在同一个列表中查找用户名和密码似乎很奇怪......)请提供minimal reproducible example。 -
假设用户是
List<Student>,那么您的#contains调用就会出错。我冒昧地猜测您使用的是原始类型列表,它允许您首先执行此操作。展示您如何设置users字段。 -
你应该遵循 Java 命名约定:方法名是用驼峰命名的。