当整数输出超过“9”时打印语句变得混乱后,如何修复打印语句的格式?
How do I fix the formatting of my print statement after it gets messed up when an integer output goes over "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);
}
}
不要使用所有连接,使用 formatted 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 是一个换行符(这个不从参数列表中取值)。
Documentation for format string here.
格式化程序出现在很多地方。如图所示,有“printf”、String.format 方法等。
为了不让代码淹没我的问题,我编写了一个片段来重现与原始代码相同的问题。正如标题所述,在其中一个整数(特别是 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);
}
}
不要使用所有连接,使用 formatted 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 是一个换行符(这个不从参数列表中取值)。
Documentation for format string here.
格式化程序出现在很多地方。如图所示,有“printf”、String.format 方法等。