2012-04-22 121 views
0

這個程序讀取的文本文件,在這種情況下,讀取了這一位:While循環執行的次數太多

Sam 

5 0 0 0 

Dave 

5 5 0 0 

Bill 

5 -5 0 0 

Louise 

3 3 5 0 

早在我的計劃,我執行下面的while循環:

  int count = 0; 


     while (input.hasNextLine()) 
     { 

      count++; 

      if (count % 2 == 1) //for every other line, reads the name 
      { 
       String line = input.nextLine(); 
       names.add(line); //puts name into array 
      } 

      if (count % 2 == 0) //for every other line, reads the ratings 
      { 
       ArrayList<Integer> rtemp = new ArrayList<Integer>(); 
       while (input.hasNextInt()) 
       { 
        int tempInt = input.nextInt(); 
        rtemp.add(tempInt); 
       }    
       allratings.add(rtemp); 

      } 


     } 

出於某種原因,在這個while循環完成時,int count是14.我只希望它在8,並認爲它應該是,考慮到只有8行文本,它應該是爲每一行執行。顯然,這在程序的後期會引起很大的問題。任何想法是怎麼回事?

+1

該文件是否有像您的示例顯示的空行? – 2012-04-22 14:42:48

+0

是的,包括我認爲是正確的14個空格。 – 2012-04-22 14:54:33

+0

不,它不。我只需要這樣做來格式化它。 – WAMoz56 2012-04-22 14:54:49

回答

0

從您的第二個循環看來,光標永遠不會移動到下一行......我在allratings.add(rtemp);之後的下方添加了行,它工作正常。

if(input.hasNext()) 
    input.next(); 
+1

你,我的朋友,是一個天才。 – WAMoz56 2012-04-22 15:42:55

+0

如果您認爲它對您有幫助,請將其選爲正確答案。 – 2012-04-22 15:50:03