【问题标题】:An error saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" shows up when I run my code当我运行我的代码时出现一个错误,说“线程中的异常”main“java.lang.ArrayIndexOutOfBoundsException:-1”
【发布时间】:2021-05-21 07:05:56
【问题描述】:

这是我的代码:

    Scanner input= new Scanner (System.in);
    
    int[][] anArray= new int[2][2];
    int[][] anArray1= new int[2][2];
    int[][] anArray2= new int[2][2];
    int temp1=1, temp2=1;
    
    for(int a=0; a<anArray.length; a++){
        for(int b=0; b<anArray.length; b++){
            System.out.println("Enter value in anArray index["+a+"]["+b+"]:");
            anArray[a][b]= input.nextInt();
            
            System.out.println("Enter value in anArray1 index["+a+"]["+b+"]:");
            anArray[a][b]= input.nextInt();
        }
    for(int c=0; c<anArray2.length; c++){
        for(int d=0; d<anArray2.length; d++){
            anArray2[c][d]=anArray[c][d] + anArray1[temp1][temp2];
            System.out.println("Total of "+ anArray[c][d]+ " and "+ anArray1[temp1][temp2]+ " is " + anArray2[c][d]);
        temp2--;
    }
        temp1--;
        temp2=1;
    }
    }

这是我班上的实验室。一旦我模拟了它,我就不太明白涉及 temp1 和 temp2 的这些代码部分

    int temp1=1, temp2=1;

    anArray2[c][d]=anArray[c][d] + anArray1[temp1][temp2];

错误行在这里:

    anArray2[c][d]=anArray[c][d] + anArray1[temp1][temp2];

请大家帮忙

【问题讨论】:

  • 数组的 java 索引有效:0 -> array.length-1。 -1 不是一个有效的索引,那是你的问题。
  • 您正在减去 for 循环中的值,您用作索引的值,这可能是问题所在。
  • 用你自己的话来说,你认为错误信息是什么意思?用您自己的话来说,如果一个数组的长度为 N,您认为哪些数字应该是该数组的有效索引?当您尝试使用调试器检查用于索引数组的值时发生了什么?它们对你有意义吗?他们是你所期望的吗?如果不是,你能理解计算是如何出错的吗?当你试图追踪计算的逻辑时发生了什么?
  • temp1 变成 -1 导致 ArrayIndexOutOfBoundException,所以,检查你的逻辑。
  • @Stultuske 那么我教授的代码错了吗?他是编写代码的人。

标签: java exception multidimensional-array


【解决方案1】:

在这一行:

System.out.println("Enter value in anArray1 index["+a+"]["+b+"]:"); anArray[a][b]= input.nextInt();

您输入的是 anArray[a][b] = input.nextInt(); 而不是 anArray1[a][b] = input.nextInt();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多