gpt4 book ai didi

java - java中有没有像setw()这样的内置函数?如果不是,我该如何格式化它?

转载 作者:行者123 更新时间:2023-12-02 06:28:30 26 4
gpt4 key购买 nike

如何格式化字符串和数字(​​ double 、整数等)?

我尝试过 %-10s 和 %10.2f

String c1="Java";
String c2="Visual Basic";

System.out.printf("%-30s %d \tPass\n",c1,100);
System.out.printf("%-30s %d \tFail\n",c2,20);

我预计输出应该是

Java                          100   Pass
Visual Basic 20 Fail

但实际输出是

Java                           100  Pass
Visual Basic 20 Fail

最佳答案

您的代码不会产生您所说的输出,它会产生:

Java                           100  PassVisual Basic                   20   Fail

If the problem is that the 20 is aligned with the left side of the 100 rather than the right, just add an appropriate width to your output of the number (for instance, %3d):

String c1="Java";
String c2="Visual Basic";

System.out.printf("%-30s %3d \tPass\n", c1, 100);
System.out.printf("%-30s %3d \tFail\n", c2, 20);

输出:

Java                           100  PassVisual Basic                    20  Fail

Live example

关于java - java中有没有像setw()这样的内置函数?如果不是,我该如何格式化它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55771692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com