我如何将它变成 table 输出?

How do I make this into a table output?

问题是要求我掷两个骰子并将它们的输出分别打印在两个单独的列中,然后为两次掷骰的总和创建第三列。

import java.util.Random;

public class DiceRolls {
    public static void main(String[] args) {
        System.out.println("Dice 1\tDice 2");
        Random ran = new Random();

        int numberOne;
        for (int x = 0; x < 7; x++) {
            numberOne = ran.nextInt(6) + 1;
            System.out.println(numberOne);
        }

        int numberTwo;
        for (int y = 0; y < 7; y++) {
            numberTwo = ran.nextInt(6) + 1;
            System.out.println("    " + numberTwo);
        }
    }
}

我认为您正在以错误的方式思考这个问题,并试图遍历一个骰子的所有掷骰,THEN 遍历另一个骰子。如果您尝试同时掷两个骰子,然后将它们相加并打印输出,它会使事情变得简单得多:

    //How many runs you want
    int numRuns = 7;

    for (int x = 0; x < numRuns; x++) {
        Random ran = new Random();
        int dieOne = ran.nextInt(6) + 1;
        int dieTwo = ran.nextInt(6) + 1;
        System.out.format("| Die 1:%3d| Die 2:%3d| Total:%3d|\n", dieOne, dieTwo, dieOne + dieTwo);
    }

此代码将掷两个骰子 7 次并将它们相加。您可以更改 numRuns 的值以更改它为 运行 的次数。然后,您可以使用 System.out.formatString.format 创建格式化输出。

String.formatSystem.out.format 所做的基本上是使用 %3d 来放置变量,例如 dieOne,在 String 内部以格式化方式。这个 %3d 的例子可以分解成 3 个基本部分。

  • 其中3代表字符数允许变量 使用,用多余的空格填充未使用的字符。

  • d是变量的类型(在本例中是int

  • %用来表示String
    中有一个变量 在那个位置。

所以综上所述:%3d用于将dieOnedieTwodieOne + dieTwo的值分别设置到String中作为int每个总共有3个字符

在下面的编辑示例中,%4d%4d%5d 总共有 4、4 和 5 个 个字符dieOnedieTwodieOne + dieTwo分别设置为。选择的字符数用于匹配 Die1Die2Total.

的 headers 的宽度

编辑: 如果你想让它看起来更像 table 你可以这样打印它:

    //How many runs you want
    int numRuns = 7;

    System.out.println("-----------------");
    System.out.println("|Die1|Die2|Total|");
    System.out.println("-----------------");
    for (int x = 0; x < numRuns; x++) {
        Random ran = new Random();
        int dieOne = ran.nextInt(6) + 1;
        int dieTwo = ran.nextInt(6) + 1;
        System.out.format("|%4d|%4d|%5d|\n", dieOne, dieTwo, dieOne + dieTwo);
    }
    System.out.println("-----------------");