loading...

JAVA: Write a program to format output strings

inspire99 profile image Ganesh Swamypillai Updated on ・1 min read

Requirement: Add leading zeros to integers and string should be left justified with 15 length.

package com.technoparadigms.strings.formatting;
import java.util.Scanner;

public class 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("================================");

}

}

From above program, we see the following

We use String.format("%03d") -- this is used to add leading zeros to the number
Please note that we use System.out.printf() -- this respects formatted output in format specifier as part of arguments.
We use "%15s" -- this is to specify that the string will be left justified with 15 length. The next string will be away atleast of 15 length ( minus length of the string .. for example: if 'java' is the string, then we have already taken 4 letters out of 15, remaining is 11.. so there will be 11 spaces. After these 11 spaces, there will be the next string in the argument printed.
Key takeaways:

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

Discussion

pic
Editor guide