我想创建一个 2D 字符串数组,用于存储作为键盘输入给出的名称和地址。 例如:姓名1 地址1; 姓名 2 地址 2;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[][] array = new String[3][2];
for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
array[i][j] = sc.nextLine();
}
System.out.println(array[0][0]);
}
}
在这里我想打印一份要求输入姓名的声明 例如。 System.out.println("请输入姓名:"); 之后我想写另一份声明要求输入地址 eg.System.out.println("请输入地址"); 但我不知道如何在二维数组中做到这一点
最佳答案
像这样怎么样?
public static void main(String[] args) {
int rows = 3;
int cols = 2;
Scanner sc = new Scanner(System.in);
String[][] array = new String[rows][cols];
for (int row = 0; row < rows; row++) {
System.out.println("Enter name:");
array[row][0] = sc.nextLine();
System.out.println("Enter the address:");
array[row][1] = sc.nextLine();
}
// Print out array
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.print(array[row][col] + ", ");
}
System.out.print(";");
}
}
输出:
Person 1, Address 1, ; Person 2, Address 2, ; Person 3, Address 3, ;
在这里实时查看:https://onlinegdb.com/Byu4wc1vI
希望这会有所帮助!
关于java - 如何在java中将2个键盘输入放入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60934078/