首页 > 解决方案 > 当整数输出超过“9”时打印语句被弄乱后,如何修复它的格式?

问题描述

为了不让代码淹没我的问题,我编写了一个片段来重现与原始代码相同的问题。正如标题所述,我的记分牌的打印语句在其中一个整数(特别是aiScore)超过 9 后变得混乱。我将如何解决这个问题?有没有更好的方法来格式化我的打印语句?我提供了一张aiScore9 点前后的照片。

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

在此处输入图像描述

标签: javaformatting

解决方案


不要使用所有的连接,使用格式化的 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 是一个换行符(这个不从参数列表中获取值)。

格式字符串的文档here

格式化程序出现在各个地方。如图所示,有“printf”、String.format 方法等等。


推荐阅读