菜鸟到编程...我需要创建一个函数来接收 2d 数组并请求用户输入以填充行和列。显示我的错误是最后一行的"空语句"/"不是语句"。
public static void fillMatrix(int [][] pmatrix) throws IOException {
int [][] matrix = new int [pmatrix.length][pmatrix.length];
int i, k; //loop variables
int rows, columns;
for(i = 0; i < pmatrix.length; i++){
print.println("set the value of the row " + (i + 1));
rows = Integer.parseInt(read.readLine());
}
for(k = 0; k < pmatrix.length; k++){
print.println("set the value of the column " + (k + 1));
colums = Integer.parseInt(read.readLine());
}
matrix = {{rows}, {columns}};
}
首先,您在此处要做的是在每次迭代中重新分配变量rows
和columns
。因此,最后,矩阵中每行都有一个值。
其次,您将局部变量matrix
重新分配为矩阵,该矩阵具有两行和一列。由于它与参数pmatrix
没有任何关系,因此该方法返回后不会发生任何事情。
我假设您想在空的 2D 数组上调用该方法,并用控制台中的值填充它。要遍历 2D 数组,您需要一个嵌套的 for 循环并单独访问矩阵中的每个索引:
public static void fillMatrix(int [][] pmatrix) throws IOException {
for(i = 0; i < pmatrix.length; i++){
for(int j = 0; j < pmatrix[i].length; i++ {
print.println("set the value of row " + (i + 1) + " in column " + (j + 1));
pmatrix[i][j] = Integer.parseInt(read.readLine());
}
}
}
在完整的上下文中更容易理解。下面的代码有一个 main 方法,用于创建大小为 3x3 的矩阵,如果您愿意,可以更改它。接下来,它调用 fillMatrix
方法,然后调用 printMatrix
方法。
fillMatrix
遍历每一行,对于每一行,它遍历每一列。对于矩阵中的条目,它使用 Scanner
而不是 BufferedReader
读取整数,因为它更易于使用。
printMatrix
遍历所有条目并将它们打印为表格。
运行程序并提供1 2 3 4 5 6 7 8 9
打印
1 2 3
4 5 6
7 8 9
该计划
import java.io.IOException;
import java.util.Scanner;
public class Helper {
public static void main(final String[] args) throws IOException {
final int[][] matrix = new int[3][3];
fillMatrix(matrix);
printMatrix(matrix);
}
public static void fillMatrix(final int[][] matrix) throws IOException {
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
final int userInput = scanner.nextInt();
row[j] = userInput;
}
}
}
private static void printMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " ");
}
System.out.println();
}
}
}