Java数组索引超出界限异常

时间:2015-04-21 01:55:23

标签: java

我在线程“main”中收到错误异常java.lang.ArrayIndexOutOfBoundsException:0     在sorting.main(sorting.java:53)。我只是尝试将字符串整数值传递给整数数组,但它没有按预期工作。我有上面的变量,例如count,这取决于用户想要输入多少个整数。在和另一个变量int[] list = new int[count];这是我试图将它们传递给的整数数组。如果我为计数输入5的值,我试图只接受5个整数值。将它们传递到int[] list数组是我搞砸的地方。

// Prompts user to enter the integer values here
while(true){
   System.out.print("\nEnter integer values here seperated by a space: ");
   intValues = input.readLine();
   String[] intCheck = intValues.split("\\s+");

   try {
      for(int j = 0; j < intCheck.length; j++){
           list[j] = Integer.parseInt(intCheck[j]);     // LINE 53 IS HERE
      }
   }
   catch (NumberFormatException ex) {
      System.err.println("You need to enter valid integer numbers. Try again.");
   }     
}  

2 个答案:

答案 0 :(得分:0)

你可能在末尾有一个额外的空间,所以你的分裂返回一个超大数组。使用j&lt;计数。

答案 1 :(得分:0)

我收到了我的错误。我很早就宣布了int count = 0。然后就在下面,我宣布int[] list = new int[count]取0值。在我提示用户输入信息后,我应该声明范围。

相关问题