我正在为一个分配做这个问题,我们必须逐个元素地添加两个矩阵,这是输出:
[0] [1] [2] [3]
[0] 14 14 15 11
[1] 8 9 14 11
[2] 10 18 7 16
[3] 4 12 11 8
我的主要问题是如何摆脱显示在矩阵顶部和左侧的方括号。这是代码:
package question1;
import java.util.Scanner;
public class Question1 {
public static void initialize(int[][] a) {
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
a[i][j] = (int)Math.ceil(Math.random() * 9);
System.out.print(a[i][j] + "\t");
}
System.out.print("\n");
}
}
public static int[][] sum(int[][] a, int[][] b) {
int[][] result = new int[a.length][a[0].length];
for(int row = 0; row<a.length; row++){
for(int col = 0; col<a[row].length; col++){
result[row][col] = a[row][col] + b[row][col];
}
}
return result;
}
public static void printArray(int[][] a) {
System.out.println("\t");
for (int col=0; col<a[0].length; col++) {
System.out.print("[" + col + "]\t");
}
System.out.println();
for (int row=0; row<a.length; row++) {
System.out.print("[" + row + "]\t");
for (int col=0; col<a[row].length; col++) {
System.out.print(a[row][col] + "\t");
}
System.out.println();
}
}
public static void main(String[] args){
Scanner keyb = new Scanner(System.in);
System.out.println("Enter the rows and columns for the first matrix (row followed by columns):");
int row1 = keyb.nextInt();
int col1 = keyb.nextInt();
int[][] c1 = new int[row1][col1];
System.out.println("Your first matrix is:");
System.out.println("-------------------------------");
initialize(c1);
System.out.println("-------------------------------");
System.out.println("Enter the rows and columns for the second matrix (row followed by columns):");
int row2 = keyb.nextInt();
int col2 = keyb.nextInt();
int[][] c2 = new int[row2][col2];
System.out.println("Your second matrix is:");
System.out.println("-------------------------------");
initialize(c2);
System.out.println("-------------------------------");
System.out.println();
System.out.println("The sum of your arrays are:");
System.out.println("-------------------------------");
int [][] result;
result = sum(c1, c2);
printArray(result);
System.out.println("-------------------------------");
}
}
答案 0 :(得分:1)
只需修改printArray()
方法,使用空格代替列标题和行标题的括号:
public static void printArray(int[][] a) {
System.out.println("\t");
for (int col=0; col < a[0].length; col++) {
System.out.print(" " + col + " \t"); // use spaces instead of brackets
}
System.out.println();
for (int row=0; row < a.length; row++) {
System.out.print(" " + row + " \t"); // use spaces not brackets
for (int col=0; col < a[row].length; col++) {
System.out.print(a[row][col] + "\t");
}
System.out.println();
}
}