2015-12-11 116 views
0

我正在寫一個小程序,它讀取輸入並設置數組大小,填充數組並添加數字。我的問題是,雖然我沒有得到任何錯誤,但程序停止後。任何指針,我什麼做錯了將非常感激。while循環後程序停止

public class test { 

    public static void main(String[] args) { 

     Scanner in = new Scanner(System.in); 

     int[] numbers = new int[in.nextInt()]; 
     int sum = 0; 
     System.out.println("\n" + "numbers: " + numbers.length); 

     while (in.hasNextLine()) { 

      for (int i = 0; i < numbers.length; i++) { 
       numbers[i] = in.nextInt(); 
       // System.out.println(numbers[i]); 
      } 
     } 
     for (int i = 0; i <= numbers.length; i++) { 
      sum += numbers[i]; 

     } 
     System.out.println(sum); 

    } 

} 
+1

'我<= numbers.length'採取'='出來 – Ramanlfc

+0

它不能 「停止」。也許它仍在等待你的輸入。 – Stultuske

+0

「停」你的意思是默默退出?拋出異常? ... –

回答

2

不需要while

  for (int i = 0; i < numbers.length; i++) { 
       if(in.hasNextInt()) 
       numbers[i] = in.nextInt(); 
       // System.out.println(numbers[i]); 
      } 
3

由於JavaDoc中Scanner.hashNextLine()狀態:

返回true,如果有在此掃描器輸入另一條線。 此方法可能會在等待輸入時阻塞。掃描儀不會 超過任何輸入。

因此while循環將永遠不會結束:

while (in.hasNextLine()) 

只是刪除這個循環中,你的循環內已經做了合適的工作。

PS:隨着jipr311指出解決您的第二個for循環,或者你將面臨ArrayIndexOutOfBoundsException

for (int i = 0; i < numbers.length; i++) { 
    sum += numbers[i]; 
} 
2

是沒有用while循環。刪除。 和編輯for循環像

for (int i = 0; i < numbers.length; i++)

2

這應該工作:

public static void main(String[] args) { 

     Scanner in = null; 
     try{ 
      in = new Scanner(System.in); 
      int[] numbers = new int[in.nextInt()]; 
      int sum = 0; 
      System.out.println("\n" + "numbers: " + numbers.length); 
      int count = 0; 
      while (count < numbers.length) { 
       numbers[count] = in.nextInt(); 
       count++; 
      } 
      for (int i = 0; i < numbers.length; i++) { 
       sum += numbers[i]; 

      } 
      System.out.println(sum); 
     }finally{ 
      if(null != in){ 
       in.close(); 
      } 
     } 

    } 

也有在節目資源泄漏的掃描對象沒有被關閉。我已糾正它。