2012-05-15 62 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;打破循环。