我编写了代码来制作一个具有随机列和行的表格,对于表格中的每个位置,程序要求用户写出里面的内容。对于输入,我使用扫描仪。我的问题是,如何打印用户输入的表格?您能解释一下它是如何完成的以及为什么吗?谢谢
public static void main(String[] args) {
int row = (int)(Math.random() * 5 + 1);
int column =(int)(Math.random() * 5 + 1);
String[][] table = new String [row][column];
Scanner read = new Scanner(System.in);
//String word = "";
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
System.out.print("Write a name of a fruit: ");
String word = read.next();
最佳答案
您需要首先获取用户输入并将其存储在表中
将代码更改为:
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print("Write a name of a fruit: ");
String word = read.nextLine();
table[i][j] = word;
}
}
在此之后,如果您希望以表格格式打印用户给定的水果名称,您应该添加以下代码
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(" | " + table[i][j]);
}
System.out.print(" |");
System.out.println();
}
我们在这里所做的是循环遍历每一行的列。当我们到达列的末尾时,我们打印一个新行,以便下一行打印在一个新行中。我添加了 |
(管道)来显示每列之间的边界。
对于 2X2 表格,输出将如下所示:
| Mango | Raspberry |
| Strawberry | Apple |
注意:您也可以使用初始 for 循环来显示值。但为了清晰理解,我选择创建另一组循环。
关于java - 使用扫描仪输入时如何写出表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308901/