java - 当整数输出超过“9”时打印语句被弄乱后,如何修复它的格式?
问题描述
为了不让代码淹没我的问题,我编写了一个片段来重现与原始代码相同的问题。正如标题所述,我的记分牌的打印语句在其中一个整数(特别是aiScore
)超过 9 后变得混乱。我将如何解决这个问题?有没有更好的方法来格式化我的打印语句?我提供了一张aiScore
9 点前后的照片。
public class Main
{
public static void main(String[] args) {
int playerScore = 0;
int aiScore = 10;
int ties = 0;
int gamesPlayed = 0;
System.out.println("\tPlayer Wins" + "\t CPU Wins" + "\t Ties" + "\t Games Played");
System.out.println("\t " + playerScore + "\t\t " + aiScore + "\t\t " + ties + "\t " + gamesPlayed);
}
}
解决方案
不要使用所有的连接,使用格式化的 print。
System.out.printf(" %10s %10s %10s%n", "heading1", "heading2", "heading3");
System.out.printf(" %10d %10d %10d%n", num1, num2, num3);
在这个例子中,我碰巧有 3 个数值要打印在列中,而且我碰巧相信 10 个字符足够宽。
根据您的需要进行调整。
%s 是一个通用字符串字段。%d 是十进制整数。%n 是一个换行符(这个不从参数列表中获取值)。
格式化程序出现在各个地方。如图所示,有“printf”、String.format 方法等等。
推荐阅读
- python - 每个进程运行多个蜘蛛 - 不保存输出数据
- symfony - Symfony 命令的 Docker 执行:权限被拒绝
- crop - 如何从android表面的媒体编解码器的dequeoutputbuffer裁剪视频缓冲区?
- laravel - 我如何测试 Laravel 护照 API 端点
- java - CodeSignal 几乎IncreasingSequence - 为什么这个测试用例会失败?
- angular - 如何在 Angular 7 中将表格数据导出为 PDF 和打印功能?
- vb.net - 如何使公共子窗体 ShowDialog
- java - CI/CD - 在发布分支、管道或源代码构建上标记 jar 工件?
- javascript - 为什么 json_encoded 数据不显示
- html - Angular:粘性生成的列