检查两组数字是否相等错误

时间:2013-10-04 08:10:44

标签: java arrays for-loop

我收到了这个错误:

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

指的是代码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 个答案:

答案 0 :(得分:0)

现阶段

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

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

因此超出界限

答案 1 :(得分: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循环后添加结束}

答案 2 :(得分:0)

您应该在加载代码后将k的值重置为0。或者你可以在循环标题中定义它。

for(int k = 0; k < x.length; k++)
{
    // Your code here.
}

答案 3 :(得分:0)

此循环完成之后:

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]将超出范围