我已经尝试了三天来解决这个练习,但我不会得到它。这个想法是创建一个递增的矩阵。程序询问行和列的大小,然后创建矩阵。
我举一个预期结果的例子:
1 2 3 4
5 6 7 8
这是我得到的:
1 1 1 1
1 1 1 1
这是我的代码:
public static void main (String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader
(System.in));
// User enters row and column size of the 2D array.
System.out.print ("Input row size: ");
int ro = Integer.parseInt(in.readLine());
System.out.print ("Input column size: ");
int co = Integer.parseInt(in.readLine());
System.out.println (" Array is " + ro + "x" + co);
// Creating a 2D array.
int[][] a = new int[ro][co];
// User enters values, which are put into the array.
// This is the part where the code fails.
System.out.print ("The matrix has " + ro*co + " integer values");
System.out.println (" (one per line): ");
for (int r = 0; r < a.length; r++)
for (int c = 0; c < a[0].length; c++) {
a [r][c] +=1;
}
// Printing the matrix
System.out.println ("Matrix:");
for (int r = 0; r < a.length; r++) {
for (int c = 0; c < a[0].length; c++)
System.out.print (a[r][c] + " ");
System.out.println();
}
}