首页 > 解决方案 > 如何将其转换为表格输出?

问题描述

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

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

标签: javadice

解决方案


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

    //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代表允许变量使用的字符数,未使用的字符用额外的空格填充。

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

  • %用于表示在那个位置有一个变量String

所以总而言之:%3d用于将dieOnedieTwo、 和的值dieOne + dieTwo分别设置Stringint, 共 3 个字符

在下面的编辑示例中,%4d%4d%5d总共有 4、4 和 5 个字符,分别设置为dieOnedieTwo和。dieOne + dieTwo选择的字符数用于匹配 、 和 的Die1标题Die2宽度Total

编辑: 如果你想让它看起来更像一张桌子,你可以像这样打印它:

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

推荐阅读