gpt4 book ai didi

java - 二维数组帮助 - 乘以负数

转载 作者:行者123 更新时间:2023-12-01 14:48:09 24 4
gpt4 key购买 nike

错误消息是 - 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 2

我将一个二维数组传递给一个方法,并将数组内的值乘以 2。这是下面的方法。

当我从 main 传入第一个数组而不是第二个数组时,它可以正常工作 - 这些也显示在方法代码下方

有人知道如何修改这个错误吗?我也无法对循环迭代等进行硬编码

int setuparray2 [][] = new int [][] {{4, 5},{6, 9} };                               
int setuparray3 [][] = new int [][] {{4, 6, 3},{-1,9,-5}};

scalarMultiplication(2,setuparray1);
scalarMultiplication(2,setuparray3);


public static void scalarMultiplication( int factor, int[][] a)
{
//creates a new array to hold the multiplied value
int multiplyArray [][] = new int [a.length][a.length];

for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < a[i].length; j++)
{
//multiplys each element in the array by the factor
multiplyArray[i][j] = a[i][j] * factor;
}
}
//prints the array with the results
printArray(multiplyArray);
}

最佳答案

创建multiplyArray时,您没有预留足够的空间。

而不是:

int multiplyArray [][] = new int [a.length][a.length];

写:

int multiplyArray [][] = new int [a.length][a[0].length];

关于java - 二维数组帮助 - 乘以负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15187443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com