0

I'm getting this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

which is referring to this line in the code if(x[k]==y[j])

Scanner sc1 = new Scanner(System.in);        
    int [] x;
    int [] y;
    int size;
    System.out.println("Numbers in launch code sequence should be entered on ");
    System.out.println("single line, separated by blanks.");
    System.out.println("");
    System.out.println("Enter length of launch code sequence: ");        
    size = sc1.nextInt();
    x = new int[size];
    y = new int[size];
    int k = 0;
    int j = 0;
    System.out.println("Mr. President, Enter the launch code sequence: ");
    for(;k<x.length; k++){         
    x[k] = sc1.nextInt();}
    System.out.println("Mr. Vice President, Enter the launch code sequence");
    for(;j<y.length; j++){
    y[j] = sc1.nextInt();      
            if(x[k]==y[j]){
                System.out.println("All equal: Missile system cleared for launch.");

            if(x[k]!=y[j]){
                System.out.println("Codes do not check out. Abort missile launch.");
            }
        }
    }
}
4

4 回答 4

0

你的代码

  • 遍历 x 数组;之后,k == x.length
  • 遍历 y 数组;在此迭代中,您与 x[k] 进行比较,这超出了 x 的范围

我猜你真正想做的是两个嵌套循环 - 在这种情况下,改变

  for(;k<x.length; k++){         
    x[k] = sc1.nextInt();}

for(;k<x.length; k++){         
    x[k] = sc1.nextInt();

}并在 y 循环之后添加关闭。

于 2013-10-04T08:17:45.943 回答
0

加载完代码后,您应该将值重置k回。0或者你可以在循环头中定义它。

for(int k = 0; k < x.length; k++)
{
    // Your code here.
}
于 2013-10-04T08:17:49.220 回答
0

在此 for 循环完成后:

for(;k<x.length; k++){         
    x[k] = sc1.nextInt();}

k 的值为 x.length

k == x.length //will be true. because the k will be incremented and the condition k<x.length will be checked. this is how the for loop functions

在下一个 for 循环中您正在访问

x[k] // equivlent of  x[x.length] which is out of abounds

允许访问的最大索引是x[x.length-1]因为在 java 数组中索引从 0 开始

因此异常 ArrayIndexOutofBounds, x[k] 将超出范围

于 2013-10-04T08:18:14.737 回答
0

在这个阶段

if(x[k]==y[j]){

k已完成对其数组的迭代并将设置为x.length

因此超出范围

于 2013-10-04T08:13:26.477 回答