JAVA:编写程序以格式化输出字符串

要求:将前导零添加到整数,并且字符串应以15个长度对齐。

包com.technoparadigms.strings.formatting; 导入java.util.Scanner;

公共类OutputFormatting {

public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i=0;i<3;i++){
            String s1=sc.next();
            int x=sc.nextInt();
            // Convert 
            //java 100
            //java           100
            // first string to be left justified, of 15 length
            // the number should have leading zeros, of max 3 length
            String number = String.format("%03d",x);
            System.out.printf("%-15s%s", s1,number);
            System.out.println();
        }
        System.out.println("================================");

}

}

从上面的程序中,我们看到以下内容

我们使用String.format(“%03d”)-用于将前导零添加到数字 请注意,我们使用System.out.printf()-这尊重格式说明符中的格式化输出作为参数的一部分。 我们使用“%15s”-这是指定字符串将以15个长度对齐。 下一个字符串的长度至少为15(例如,减去字符串的长度..:例如,如果'java'是字符串,那么我们已经从15个字母中取了4个字母,其余为11个。因此会有11个字母。 在这11个空格之后,将在参数中打印下一个字符串。 关键要点:

To read more on the same, check my blog: https://gansai.blogspot.com/2020/03/java-write-program-to-format-output.html

from: https://dev.to//inspire99/java-write-a-program-to-format-output-strings-4dkc

发布了0 篇原创文章 · 获赞 0 · 访问量 678

猜你喜欢

转载自blog.csdn.net/cunxiedian8614/article/details/105690843