2011-01-31 113 views
1

所以我试着看一个输入,并计算符合某个标准的单词(或者说,排除我不想要计算的单词)。该错误是在下面的代码:Java中的无限循环

BufferedReader br; 
    BufferedWriter bw; 
    String line; 
    int identifiers = 0; 
    boolean count = false; 

    try 
    { 
     br = new BufferedReader(new FileReader("A1.input")); 
     line = br.readLine(); 

     while(line != null) 
     { 
      StringTokenizer t = new StringTokenizer(line); 
      String word; 
      System.out.println(t.countTokens()); //for testing, keeps printing 6 
      for(int c = 0; c < t.countTokens(); c++) 
      { 

       word = t.nextToken(); 
       count = true; 
       if(Character.isDigit(word.charAt(0))) //if word begins with a number 
       { 
        count = false; //do not count it 
       } 
       if(count == true) 
       { 
        for(String s : keywords) 
        { 
         if(s.equals(word)) //if the selected word is a keyword 
         { 
          count = false; //do not count it 
         } 
        } 
       } 

       System.out.println(word); //testing purposes 

      } 
      word = t.nextToken(); 
     } 

这里是输入文件:

INT f2(INT x, INT y) 
    BEGIN 
    z := x*x - y*y; 
RETURN z; 
END 
INT MAIN f1() 
BEGIN 
INT x; 
READ(x, "A41.input"); 
INT y; 
READ(y, "A42.input"); 
INT z; 
z := f2(x,y) + f2(y,x); 
WRITE (z, "A4.output"); 
END 

如在上面的代码中的注释说明,第一个println语句,打印6反复(表示对我说, while循环无止境地重复)。第二个“测试目的”println声明连续打印INT f2(INT x

回答

6

它看起来像你从来没有真正阅读文件的下一行。改变这个位:

try 
{ 
    br = new BufferedReader(new FileReader("A1.input")); 
    line = br.readLine(); 

    while(line != null) 
    { 

这样:

try 
{ 
    br = new BufferedReader(new FileReader("A1.input")); 

    while((line = br.readLine()) != null) 
    { 
+0

确实 线= br.readLine();需要在循环的底部找到 。 – MeBigFatGuy 2011-01-31 04:27:35

5

您对while()的使用仅对当前行进行评估;因此,它从来不是null。将其更改为if()