java - 如何将其转换为表格输出?
问题描述
问题是要求我掷两个骰子并将它们的输出分别打印在两个单独的列中,然后为两个掷骰的总和创建第三列。
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);
}
}
}
解决方案
我认为您正在以错误的方式思考这个问题,并试图循环遍历一个骰子的所有卷,然后遍历另一个骰子。如果您尝试同时掷两个骰子,然后添加它们并打印输出,这会使事情变得更简单:
//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.format
或String.format
创建格式化输出。
什么String.format
或System.out.format
所做的基本上是%3d
用来将变量,例如,以格式化的方式dieOne
放在里面。String
这个例子%3d
可以分为 3 个基本部分。
3
代表允许变量使用的字符数,未使用的字符用额外的空格填充。The
d
是变量的类型(在本例中为int
)%
用于表示在那个位置有一个变量String
。
所以总而言之:%3d
用于将dieOne
、dieTwo
、 和的值dieOne + dieTwo
分别设置String
为int
, 共 3 个字符。
在下面的编辑示例中,%4d
、%4d
、%5d
总共有 4、4 和 5 个字符,分别设置为dieOne
、dieTwo
和。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("-----------------");
推荐阅读
- c# - 从图像中获取日期
- r - 使用左表中的多个字段,右表中的一个字段合并R中的表
- c++ - C++ 正则表达式无限循环
- python - 根据之前的系列预测结果
- php - 正则表达式如何在我的 PHP 代码中工作?
- python - 在 Python 中查找两个列表之间公共项的最快方法
- django - 为什么我在登录前没有访问重置密码 URL 你能告诉我我是如何访问的吗
- python - 使用 python 读取 rtf 元数据
- python-3.x - Python 3.8 中的连续 'TypeError: 'function' object is not subscriptable'
- javascript - 当我在函数中调用它并给我类型错误(Reactjs)时,setState 不起作用