如何从右边对齐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
How to align the output in java from right?
提问by Milan kc
I want to align my output in java as follows:
我想在 java 中对齐我的输出,如下所示:
1234
*3406
----------------
7404
0
4936
3702
-----------------
4201004
回答by MeBigFatGuy
you can use String.format
你可以使用 String.format
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...)
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
specifically, patterns like
具体来说,像这样的模式
"%8d"
“%8d”
回答by Masudul
Use System.out.printf
like 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);
}
}