线程ArrayIndex中的异常

时间:2012-11-10 13:54:04

标签: java arrays

我正在用系列和输入做一些初学者编程,但我经常遇到同样的问题。可以找到解决方案。基本上我想要我的程序现在要做的事情我输入一个数字列表并将它们打印出来。我得到了无论我在程序中发生什么变化都会出现同样的错误。这是我的代码。

import java.util.Scanner;
public class Test437 {  
public static void main(String[] args) {

  int limit = 25;
  int cnt; 
  int addtion; 
  double dbt; //Devided by two % 2

  Scanner input = new Scanner(System.in);     
  int [] ya = new int[8]; 

  for(cnt = 0;cnt < ya.length;cnt++)
  {

      System.out.print("ya[" + cnt + "]= ");
      ya[cnt] = input.nextInt();

  }

      System.out.println(ya[cnt]);


  }
  }

我收到此错误: 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:8         在Test437.main(Test437.java:22)

4 个答案:

答案 0 :(得分:1)

System.out.println(ya[cnt]);此行在外部循环。 Cnt等于数组大小,因此不能以这种方式使用它,因为数组中没有带有这种索引的元素。

答案 1 :(得分:0)

离开循环的条件是超过长度,因此你得到indexoutofbounds

答案 2 :(得分:0)

这一行

        System.out.println(ya[cnt]);

正在尝试访问ya.Length索引中不存在的元素。

在你的例子中,ya [8]包含从0到7位置的元素(ya [0] ya [1] ... ya [7]并且你试图访问ya [8] bacuase cnt变量是8在for语句结束后。

因此编译器会抛出indexOutOfBounds异常。

答案 3 :(得分:0)

该行:

System.out.println(ya[cnt]);

需要再次循环以在接受它们之后打印出所有数组值:

for (cnt = 0;cnt < ya.length;cnt++) {
   System.out.println(ya[cnt]);
}

或者,您可以这样做:

System.out.println(Arrays.toString(ya));
相关问题