2012-05-15 63 views
1

我有這樣的功能:爪哇 - 問題與閱讀文件

public static int checkRank(String lineToCompare){ 
    int rank = 0; 
    try{ 
     // Open the file that is the first 
     // command line parameter 
     FileInputStream fstream = new FileInputStream("ranks.txt"); 

     // Get the object of DataInputStream 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

     String strLine; 
     //Read File Line By Line 
     System.out.println("SPOT 0"); 
     while ((strLine = br.readLine()) != null) { 
      //Compare the line with the line to compare (string) 
      System.out.println("SPOT 1"); 
      if(strLine.trim().equals(lineToCompare)) { 
       //I found it! Read the next line... 
       final String lineAfter = br.readLine(); 
       rank = Integer.parseInt(lineAfter); 
       System.out.println("SPOT 2"); 
      }else{ 
       rank = 0; 
       System.out.println("SPOT 3"); 
      } 
     } 

     //Close the input stream 
     in.close(); 
    }catch (Exception e){//Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    } 

    System.out.println("Username: " + lineToCompare + " | Rank: " + rank); 
    return rank; 
} 

ranks.txt文件如下:

test1 
2 
test2 
1 

控制檯輸出(以下簡稱 「SPOT」 S只是用於調試) :

[Commands] SPOT 0 
[Commands] SPOT 1 
[Commands] SPOT 2 
[Commands] SPOT 1 
[Commands] SPOT 3 
[Commands] SPOT 1 
[Commands] SPOT 3 
[Commands] Username: test1 | Rank: 0 

正如你所看到的,如果它工作正常,它會說test1的等級是2.有人可以幫助我確定問題是什麼?

+0

什麼是'lineToCompare'? – Jeffrey

+0

@Jeffrey,lineToCompare = test1(如在控制檯輸出中顯示的那樣)。 – DannyF247

+2

嘗試添加一個休息;打印SPOT2後。您在讀取「test2」之後將等級設置爲0,然後再讀取「1」時將等級設置爲0。 – ppalasek

回答

1

您應該添加一個休息;聲明在打印出「SPOT 2」以結束while循環的行之後。

如果沒有中斷,當您讀取「test2」行並且然後再讀取「1」行(while循環一直持續到文件結尾)時,您將排名設置爲0。

1

在上一次循環迭代中,您正在用0覆蓋rank

當你受到打擊時,使用break;打破循環。