如何从右边对齐java中的输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19194136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:56:26  来源:igfitidea点击:

How to align the output in java from right?

javaalignmentoutput

提问by Milan kc

I want to align my output in java as follows:

我想在 java 中对齐我的输出,如下所示:

   1234
  *3406
----------------
   7404
     0
 4936
3702
-----------------
4201004

回答by Masudul

Use System.out.printflike below:

使用 System.out.printf如下:

public class Multi {
    public static void main(String[] args) {
        int align=10;
        int a=1234;
        int b=3406;
         System.out.printf("%"+align+"d\n",a);
         System.out.printf("%"+align+"d\n",b);
         System.out.println("---------------------------");
        int res=a*b;
        while(b!=0){
            int t=b%10;            
            System.out.printf("%"+(align--)+"d\n",t*a);
            b/=10;
        }
        System.out.println("---------------------------");
        System.out.printf("%10d\n",res);

    }
}