我在这行代码中收到错误消息
arraySum [i][j] = array1 [i][j] + array2 [i][j];
并且在调用方法类时
int [][]sum = doTheMath(array1,array2, '+');
我的问题可能在于创建新的double数组,其长度与参数中的one double相同。对于我使用:6
的行,对于列,我使用:4
。
public static int [][]doTheMath(int [][]array1, int [][]array2, char arithmetic)
{
// Declares 2-dimensional array the same size as one in parameters
int [][]arraySum = new int [array1.length][array1[0].length];
for (int i = 0; i < arraySum.length; i++)
arraySum[i] = new int [array1[i].length];
// For loop to take each row and column to separately do arithmetic on
for (int i = 0; i < arraySum.length; i++) {
for (int j = 0; j < arraySum.length; j++) {
if (arithmetic == '+')
arraySum [i][j] = array1 [i][j] + array2 [i][j];
else if (arithmetic == '-')
arraySum [i][j] = array1 [i][j] - array2 [i][j];
else if (arithmetic == '*')
arraySum [i][j] = array1 [i][j] * array2 [i][j];
else if (arithmetic == '/')
arraySum [i][j] = array1 [i][j] / array2 [i][j];
else if (arithmetic == '%')
arraySum [i][j] = array1 [i][j] % array2 [i][j];
}
}
// arraySum value is returned
return arraySum;
}
数组1和数组2的值来自此方法类。
public static int getSize(String args)
{
// Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
// Declares input as integer
int input = 0;
// Will print rows or columns and take keyboard input
System.out.print(args);
input = keyboard.nextInt();
// While loop to check if input is in between 2 and 6, if not will print error
while (input < 2 || input > 6) {
System.out.print(args);
input = keyboard.nextInt();
if (input < 2 || input > 6)
System.out.println("The number your entered was not between 2 and 6.");
}
// Input value is returned
return input;
}
答案 0 :(得分:2)
这部分代码无用
for (int i = 0; i < arraySum.length; i++)
arraySum[i] = new int [array1[i].length];
作为这一行
int [][]arraySum = new int [array1.length][array1[0].length];
已经设置了array1的长度。
至于你的例外,我相信你想改变这一行
for (int j = 0; j < arraySum.length; j++)
到
for (int j = 0; j < arraySum[i].length; j++)