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

用户名

我收到此错误:

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.");
            }
        }
    }
}
弗兰克·施密特

您的验证码

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

我想您真正想做的是两个嵌套循环-在这种情况下,请更改

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

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

}在y循环后添加结束符。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章