使用打印格式均匀间隔一个或多个数字的整数显示



我正在尝试编写一个程序,该程序将显示从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,则需要两个 space.so 它们之间不会有空格。您可以删除"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();
}

检查输出是否大于 10,如果是,则添加第三个空格

public class HelloWorld{
     public static void main(String []args){
         final int UPPERLIMIT =20;
         int i=2;
         do
         {
             if(i%2 == 0){
                 if(i < 10){
                     System.out.format("%2d",i);                      
                 }
                 else{
                      System.out.format("%3d",i);                        
                 }                 
             }
             i++;
         }
         while(i<=UPPERLIMIT);
         System.out.println();   
     }
}