【问题标题】:How do I make this into a table output?如何将其转换为表格输出?
【发布时间】:2019-11-20 09:39:07
【问题描述】:

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

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

【问题讨论】:

    标签: java dice


    【解决方案1】:

    我认为您的想法是错误的,并试图循环遍历一个骰子的所有掷骰,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 个字符dieOne、@987654346 @ 和 dieOne + dieTwo 分别设置为。选择的字符数用于匹配 Die1Die2Total 的标题宽度。

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

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

    【讨论】:

    • 最后一行是做什么的 "System.out.format("|%4d|%4d|%5d|\n", dieOne, dieTwo, dieOne + dieTwo); "
    • @Cleo 为正文添加了解释。
    • 4,4,5之间的空格是什么?还有为什么你必须写 dieOne, dieTwo 然后 dieOne + dieTwo?
    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多