在Java中,要连续输入一个二维数组,你可以使用嵌套的for循环来遍历数组的每一行和每一列,并获取用户的输入。以下是一个示例代码,展示了如何实现这一过程:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 声明数组的行数和列数
System.out.println("请输入二维数组的行数:");
int rows = scanner.nextInt();
System.out.println("请输入二维数组的列数:");
int cols = scanner.nextInt();
// 初始化二维数组
int[][] array = new int[rows][cols];
// 使用嵌套循环遍历每一行和每一列
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// 获取用户输入并将其存储在数组中
System.out.println("请输入第 " + (i + 1) + " 行,第 " + (j + 1) + " 列的元素:");
array[i][j] = scanner.nextInt();
}
}
// 打印二维数组
System.out.println("输入的二维数组为:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
如果你需要输入的是字符二维数组,可以使用以下代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 声明数组的行数和列数
System.out.println("请输入二维数组的行数:");
int rows = scanner.nextInt();
System.out.println("请输入二维数组的列数:");
int cols = scanner.nextInt();
// 初始化二维数组
char[][] grid = new char[rows][cols];
// 使用嵌套循环遍历每一行和每一列
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// 获取用户输入并将其存储在数组中
System.out.println("请输入第 " + (i + 1) + " 行,第 " + (j + 1) + " 列的元素:");
grid[i][j] = scanner.next().charAt(0);
}
}
// 打印二维数组
System.out.println("输入的二维数组为:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
在这两个示例中,我们都使用了`Scanner`类来获取用户的输入。第一个示例用于整数二维数组,第二个示例用于字符二维数组。请根据你的需求选择合适的方法