2014-12-05 75 views
0

我想製作一個遊戲,我正在整理帳戶的和IM即時做文本文件,因爲我只是在玩耍,例如文本文件是,在Java中沒有正確讀取文件

用戶名
密碼

,當我運行下面的代碼,它的每一個當我輸入的信息是正確的時間運行else語句。

String player; 

Scanner loadPlayer = new Scanner(System.in); 
System.out.print("Enter Username: "); 
String username = loadPlayer.nextLine(); 
System.out.println(); 
System.out.print("Enter Passwork: "); 
String password = loadPlayer.nextLine(); 
System.out.println(); 

try { 
     File file = new File("/home/kieran/Desktop/project/accounts/"+username+".txt"); 
     FileReader fileReader = new FileReader(file); 
     BufferedReader bufferedReader = new BufferedReader(fileReader); 
     StringBuffer stringBuffer = new StringBuffer(); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
       stringBuffer.append(line); 
       stringBuffer.append("\n"); 
     } 
     fileReader.close(); 
     String userData[] = stringBuffer.toString().split("\n"); 
     System.out.println(userData[0]); 
     System.out.println(userData[1]); 
     if (userData[0] == username && userData[1] == password){ 
       player = username; 
       System.out.println(player); 
     } 
     else{ 
       System.out.println("Username, "+username+" does not exist, please try again!"); 
       loadPlayer(); 
     } 
} catch (IOException e) { 
     e.printStackTrace(); 
} 
+4

可能重複(http://stackoverflow.com/questions/513832/how-do -i-compare-strings-in-java) – BackSlash 2014-12-05 13:44:14

回答

1

你的字符串比較的實現並不確定。 替換此行

if (userData[0] == username && userData[1] == password){ 

這一個:我如何在Java中比較字符串]的

 if (userData[0].trim().equals(username.trim()) && userData[1].trim().equals(password.trim())){ 
+0

謝謝,完美的作品! – 2014-12-05 14:03:24

2
if (userData[0].equals(username) && userData[1].equals(password)){ 
    player = username; 
    System.out.println(player); 
} 
0

試試這個

if (userData[0].equals(username) && userData[1].equals(password)){ 
      player = username; 
      System.out.println(player); 
    } 
    else{ 
      System.out.println("Username, "+username+" does not exist, please try again!"); 
      loadPlayer(); 
    }