使用扫描仪输入时如何写出table?

How to write out table when using input from scanner?

我编写了代码来制作一个 table,其中包含随机的列和行,对于 table 中的每个位置,程序要求用户写下里面的内容。对于输入,我使用了扫描仪。我的问题是,如何使用用户输入打印出 table?你能解释一下它是如何完成的以及为什么吗?谢谢

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();

您需要先获取用户输入并将其存储在您的 table 中

将您的代码更改为:

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;
    }
}

在此之后,如果您希望以table格式打印用户给定的水果名称,您应该添加以下代码

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 的输出看起来像这样 table:

 | Mango | Raspberry |
 | Strawberry | Apple |

注意:您也可以使用初始的 for 循环来显示这些值。但是我选择创建另一组循环以便清楚地理解。