2012-04-15 61 views
0

我試圖讀取infile中的每個整數並將其傳遞給方法adScore,該方法確定字母等級,以及所有等級和最高考試分數和最低考試分數。但是我的while循環在執行for循環時並沒有從infile中提取數據,因爲我在執行system.out.print的for循環之後調試它。什麼回報只是數字0-29這是我的循環計數器。可以幫助我瞭解我做錯了什麼,以便我可以從infile中提取成績分數?需要從infile中取出每個整數並將其傳遞給方法

問候。

 while(infile.hasNextInt()) 
     { 
      for(int i=0; i <30; i++)//<-- it keeps looping and not pulling the integers from the  file. 
      { 
       System.out.println(""+i);//<--- I placed this here to test what it  is pulling in and it is just counting 
       //the numbers 0-29 and printing them out. How do I get each data from the infile to store 
       exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max 
      } 
     } 

回答

1

特隆的權利---你並沒有要求掃描儀讀取下一個整數。 Scanner.hasNextInt()只需測試以查看是否有要讀取的整數。你只是告訴i循環值0-29。我想你的意思是做這樣的事情:

while(infile.hasNextInt()) 
{ 
    int i = infile.nextInt(); 
    exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max 
} 

如果你不知道的是,在輸入的每一行是一個整數,你可以做這樣的事情:

while(infile.hasNext()) { // see if there's data available 
    if (infile.hasNextInt()) { // see if the next token is an int 
     int i = infile.nextInt(); // if so, get the int 
     exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max 
    } else { 
     infile.next(); // if not an int, read and ignore the next token 
    } 
} 
+0

謝謝!我一直在努力研究如何從循環中的infile中獲取數據。我不知道我是否可以使用另一個局部變量並將輸出分配給該局部變量。這就說得通了!我永遠不會忘記這一點,因爲我已經在這一連串3天的時間裏撞到了我的頭:( – SaintClaire33 2012-04-15 12:32:42

2

它打印0 - 29,因爲這是你告訴它做的事:

System.out.println(""+i) 

會打印出我,這簡直是您正在使用的循環計數器的整數。你永遠不會從掃描儀對象中檢索下一個值。我猜這是作業,所以我不會給你任何代碼,但我會說你一定需要使用Scanner的nextInt()方法來檢索輸入文件中的值,並在你的內部使用該值for循環。

+0

感謝。是的,我嘗試將infile放在那裏,但是我有一堆空白的錯誤。我試過這個來測試它:System.out.println(「」+ infile); rator = \。] [positive prefix =] [negative prefix = \ Q- \ E] [positive suffix =] [negative suffix =] [NaN string = \ Q?\ E] [infinity string = \ Q?\ E] java.util.Scanner [delimiters = \ p {javaWhitespace} +] [position = 0] [match valid = true] [need input = false] [source closed = false] [skipped = false] [group separator = \,] [decimal sepa – SaintClaire33 2012-04-15 02:16:47

相關問題