我正在尝试编写一个程序来显示从 2 到 20 的所有偶数。 我尝试使用 System.out.format 均匀地显示数字,但是一旦要显示的数字位数增加,间距就会变得不均匀。
所需的输出是:
2 4 6 8 10 12 14 16 18 20
但我得到的输出是:
2 4 6 8101214161820
这是我的源代码:
public class HelloWorld {
public static void main(String []args) {
final int UPPERLIMIT = 20;
int i = 2;
do {
if((i % 2) == 0)
System.out.format("%2d",i);
i++;
} while(i<=UPPERLIMIT);
System.out.println();
}
}
最佳答案
如果结果>=10,则需要两个空格,因此它们之间不会有空格。 您可以删除“2”并在“%d”后添加空格:
public static void main(String[] args){
final int UPPERLIMIT =20;
int i=2;
do
{
if((i%2)==0)
System.out.format("%d ",i);
i++;
}
while(i<=UPPERLIMIT);
System.out.println();
}
关于java - 使用打印格式均匀间隔一位或多位数字的整数显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42823449/