我有一個代碼,打開一個文件來檢查用戶給出的用戶名或密碼是否在文件中,但是代碼顯示登錄成功時沒有登錄。我是編程初學者,所以我需要一些幫助來修復錯誤,並且使用基本的初學者編碼,而不需要複雜的庫或方法。登錄順序的邏輯
我得到下面的輸出,這說明我的程序並不表現我怎麼想它:
USERNAME OR PASSWORD INCORRECT! TRY AGAIN
SUCCESSFUL, YOU ARE LOGGED IN!
下面是代碼:
package login;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here.
File file = new File("users.txt");
Login newLogin = new Login(file);
newLogin.checkLogin("word", "wordet");
}
}
package login;
import java.io.File;
//library for file exception
import java.io.FileNotFoundException;
import java.util.ArrayList;
//library for opening file
import java.util.Scanner;
public class Login {
private File file;
private ArrayList<String> usernames;
private ArrayList<String> passwords;
private int tries = 3;
public Login(File file) {
this.file = file;
this.usernames = new ArrayList<String>();
this.passwords = new ArrayList<String>();
this.tries = 3;
}
public void readLines() throws FileNotFoundException{
ArrayList<String> lines = new ArrayList<String>();
Scanner input = new Scanner(this.file);
while (input.hasNextLine()){
lines.add(input.nextLine());
}
input.close();
usernames.clear();
passwords.clear();
for(int i = 0; i < lines.size(); i++) {
if (i %2 == 0) {
usernames.add(lines.get(i));
} else {
passwords.add(lines.get(i));
}
}
}
public void checkLogin(String user, String pass) throws FileNotFoundException{
this.readLines();
if (tries == 0){
System.out.println("YOU HAVE TRIED TOO MANY TIMES!");
} else {
for(int i = 0; i < this.usernames.size(); i++) {
if (this.usernames.contains(user)) {
if (passwords.get(i).equals(pass)) {
System.out.println("SUCCESSFUL, YOU ARE LOGGED IN!");
} else {
System.out.println("USERNAME OR PASSWORD INCORRECT! TRY AGAIN");
tries--;
}
}
}
}
}
}
你得到的錯誤是什麼。 – tesnik03
你能顯示文件的內容嗎? – raven
請使用標題更具描述性! – Vucko