2015-12-11 69 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(); 
      } 
     } 

    } 

也有在节目资源泄漏的扫描对象没有被关闭。我已纠正它。