import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
int n, m, sumRows= 0, sumColumns= 0, i = 0, j = 0; //rows(n), Columns(m)
n = Integer.parseInt(JOptionPane.showInputDialog(null, "Rows"));
m = Integer.parseInt(JOptionPane.showInputDialog(null, "Columns"));
int[][] a = new int[n][m];
int[] b = new int[n];
int[] c = new int[m];
for(i = 0; i < a.length; i++) {
for(j = 0; j < a[i].length; j++) {
a[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Type"
+ "an int. A[" + i +"]" + "[" + j + "] = "));
sumRows+= a[i][j];
sumColumns+= a[j][i];
if(j == a[i].length-1) {
b[i] = sumRows;
sumRows= 0;
}
if(i == a.length-1) {
c[j] = sumRows;
sumRows= 0;
}
System.out.println("Sum Rows: " + sumRows+ " Vector B" + i + ": " + b[i]);
System.out.println("Sum Columns: " + sumColumns + " Vector C" + j + ": " + c[j]);
}
}
}
}
因此,我必须将行和列求和,并将它们存储在两个向量上,我必须将行之和存储在向量B中,并将列之和存储在向量C中。 行的总和可以完美地工作,但是我无法工作列的总和。
答案 0 :(得分:0)
尝试一下:
public class Main {
public static void main(String[] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog(null, "Rows"));
int m = Integer.parseInt(JOptionPane.showInputDialog(null, "Columns"));
int[][] a = new int[n][m];
int[] b = new int[n];
int[] c = new int[m];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = Integer.parseInt( JOptionPane.showInputDialog(null, "Type" + "an int. A[" + i + "]" + "[" + j + "] = "));
b[i] += a[i][j];
c[j] += a[i][j];
}
}
// USED FOR PRINTING
// -------------------------
for (int i = 0; i < b.length; i++) {
System.out.println("Sum Row " + (i + 1) + " is " + b[i]);
}
for (int i = 0; i < c.length; i++) {
System.out.println("Sum Column " + (i + 1) + " is " + c[i]);
}
// -------------------------
}
}
输入:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
输出:
Sum Row 1 is 10
Sum Row 2 is 35
Sum Row 3 is 60
Sum Row 4 is 85
Sum Column 1 is 30
Sum Column 2 is 34
Sum Column 3 is 38
Sum Column 4 is 42
Sum Column 5 is 46