我不知道我在做什麼錯了,因爲在我的主類運行該程序後,它完全跳過了如何檢查是否在通過文件/的FileWriter /掃描儀類的文本文件存在的用戶名
while(usernameCheck.hasNext()){
//code...
}
循環,即使我故意把一個用戶名已經在我的「accounts.txt」文件中。我也試過方法,但很明顯,如果我把可以說「John1」和「約翰」已經在我的accounts.txt文件,它不會接受它
import java.util.Scanner;
import java.io.*;
public class CreateAccount {
public static void newAccount() throws IOException{
Scanner keyboard = new Scanner(System.in);
FileWriter fw = new FileWriter("accounts.txt",true);
PrintWriter pw = new PrintWriter(fw);
System.out.println("Please enter a username: ");
String user = keyboard.nextLine();
File file = new File("accounts.txt");
Scanner usernameCheck = new Scanner(file);
while(usernameCheck.hasNext()){
String existingUsername = usernameCheck.nextLine();
if(user.equalsIgnoreCase(existingUsername)){
System.out.println("Username already exists");
System.out.println("Please enter a username: ");
user = keyboard.nextLine();
}
}
System.out.println("Please enter a password: ");
String pass = keyboard.nextLine();
System.out.println("Account created!");
***閱讀我的代碼後意識到我還有另外一個問題:即使我創建了一個不存在於我的「accounts.txt」類中的用戶名,由於hasNext()方法,它仍將不斷重複提示用戶名已存在。我能做些什麼呢?
什麼是您使用IDE編寫代碼?它有一個調試器嗎?如果是這樣,請遍歷代碼,看看它在做什麼。 –
@Ken White我正在使用Eclipse – Sweetcharge
然後它有一個調試器,對吧?你有沒有想過在同一個文件上同時打開'FileWriter'和'Scanner'會產生什麼問題? –