法一(模拟):
StringBuilder a=new StringBuilder(sc.next()),b=new StringBuilder(sc.next()),c=new StringBuilder(sc.next());
for(int i=0;i<8-a.length();i++)
System.out.print(" ");
System.out.print(a);
法二(格式化字符串):
int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
System.out.print(String.format("%8d",a));
/*static的方法直接用类名调用就可以了
新建一个对象调用static方法会造成空间浪费
编译器将会有警告,所以不用像下面那样创一个空字符串再来调用format方法*/
Scanner sc=new Scanner(System.in);
String a1=new String(""),b1=new String(""),c1=new String("");
int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
System.out.print(a1.format("%8d",a));
System.out.print(b1.format("%8d",b));
java数据右对齐输出
于 2022-02-22 15:56:53 首次发布