我需要我的矩阵看起来像这样。
Here are the two matrices, and the result when added:
2 2 7 4 3 4 3 3 5 6 10 7
4 4 8 8 6 8 5 5 10 12 13 13
1 9 3 7 6 8 6 9 7 17 9 16
2 3 2 9 + 4 4 7 1 = 6 7 9 10
2 9 1 1 9 8 2 5 11 17 3 6
6 1 8 4 4 8 2 2 10 9 10 6
每个数字应在输出中使用4个位置,并且+和=应该位于中间行,但是我无法获得+和=号来保留较小的数组。我的问题可能出在我的if(i == 3 && j == 3)语句上。
我这部分的代码如下。
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
// Declares 2-dimensional array the same size as one in parameters
int [][]arraySum = new int [array1.length][array1[0].length];
// Arithmetic characters to be printed when asked for
String add = "+";
String subtract = "-";
String multiply = "*";
String divide = "/";
String remainder = "%";
String equals = "=";
// If arithmetic is addition to print matrices and add them to show result
if (arithmetic == '+') {
// Text for two matrices when added
System.out.print("Here are the two matrices, and the result when added:\n");
// For loop to print array1 + array2 = sum with format
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == 3 && j == 3) {
System.out.printf("%2s", add);
}
}
System.out.print("\t");
// For loop to print out array2 and equals string
for (int k = 0; k < arraySum[i].length; k++) {
System.out.printf("%3s", array2[i][k] + " ");
if (i == 3 && k == 3) {
System.out.printf("%2s", equals);
}
}
System.out.print("\t");
// For loop to print out sum of array1 + array2
for (int l = 0; l < arraySum[i].length; l++) {
System.out.printf("%3s", sum[i][l] + " ");
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
我对3x3阵列得到的示例。 (仍应打印+或=)。
5 3 5 6 7 4 11 10 9
8 2 9 1 5 5 9 7 14
9 7 3 2 5 1 11 12 4
最佳答案
尝试if (i == arraySum.length/2 && j == arraySum[i].length-1)
。