所以我有一個名為 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");
}
}
}
當我運行它時,它會轉到“找不到用戶”,我不允許使用離線資料庫或類似的東西,這就是為什么我要隨時隨地創建用戶名而不將它們存盤在某些東西中。找不到它要查找的用戶名和密碼的原因可能是什么?順便說一句,我是一年級學生,如果可以請嘗試在不使用復雜技術的情況下解釋事物
uj5u.com熱心網友回復:
您當前正在將Student物件與學生的姓名進行比較,但有一個簡單的解決方法,假設我們有以下代碼:
List<Student> students = new ArrayList<>();
students.add(new Student("Bob", "password"));
students.add(new Student("Alice","wonderland"));
然后,當您從用戶輸入中獲取tempUsername和時tempPassword,您可以遍歷串列并檢查是否有具有該名稱和密碼的學生:
Student loggedIn = null;
for(Student student : students){
if(student.getName().equals(tempUsername) && student.checkPassword(tempPassword)){
loggedIn = student;
break;
}
}
(注意這里我為學生添加了一些 getter 和 setter 方法,現在看起來像這樣為了更好的封裝)
class Student {
private String name;
private String password;
public Student(String name, String password){
this.name = name;
this.password = password;
}
public String getName(){
return name;
}
public boolean checkPassword(String password){
return this.password.equals(password);
}
}
如果你被特別要求這樣做,那ArrayList很好,但是如果你可以使用其他資料結構,你可以考慮使用HashMaps (你可以在HashMap<String,Student>那里你可以傳遞學生的用戶名并找回學生,如果它在 中HashMap,這將是更好的時間復雜度,或者更好的是,定義您自己的可比較介面并使用HashSet,這樣您就可以進行可比較的比較用戶名,這也有助于防止添加具有相同用戶名的用戶)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/390135.html
上一篇:排列陣列,使相鄰的空間更小
下一篇:如何將查找和更新合并為1個更新
