[英]How do I fix the formatting of my print statement after it gets messed up when an integer output goes over "9"?
For the sake of not flooding my question with code, I coded a snippet that reproduces the same issue as the original code.为了不让代码淹没我的问题,我编写了一个片段来重现与原始代码相同的问题。 As the title states, the print statement for my scoreboard gets messed up after one of the integers (specifically the
aiScore
) goes over 9. How would I go about fixing this?正如标题所述,在其中一个整数(特别是
aiScore
)超过 9 后,我的记分牌的打印语句变得混乱。我将如何解决这个问题? Is there a better way which I should format my print statement?有没有更好的方法来格式化我的打印语句? I've provided a photo before and after
aiScore
goes over 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);
}
}
Don't use all that concatenation, use formatted print .不要使用所有的连接,使用格式化的 print 。
System.out.printf(" %10s %10s %10s%n", "heading1", "heading2", "heading3");
System.out.printf(" %10d %10d %10d%n", num1, num2, num3);
In this example I happen to have 3 numeric values to print in columns, and I happen to believe 10 characters is wide enough.在这个例子中,我碰巧有 3 个数值要打印在列中,而且我碰巧相信 10 个字符足够宽。
Adjust according to your needs.根据您的需要进行调整。
%s is a general string field. %s 是一个通用字符串字段。 %d is a decimal integer.
%d 是十进制 integer。 %n is a newline (this one does not take a value from the argument list).
%n 是一个换行符(这个不从参数列表中获取值)。
Documentation for format string here . 格式字符串的文档here 。
Formatters show up in various places.格式化程序出现在各个地方。 There's "printf" as shown, the String.format method, and so on.
如图所示,有“printf”、String.format 方法等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.