Java Output Formatting

  • + 2 comments

    Here we used printf to repeat the values of 0 and space. '-%15s' means that the length of string will be 15 and spaces will be repeatedly printed on right side of string. And '%03d' means length of string will be 3 and '0' will be repeatedly printed on left side of string.

    import java.util.Scanner;
    
    public class Solution {
    
    	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();
    				System.out.printf("%-15s",s1);
    				System.out.printf("%03d",x);
    				System.out.println();
    					  }
    				System.out.println("================================");
    
        }
    }
    
    • + 1 comment

      why are we use printf

      • + 0 comments

        because with printf we can print strings in a specified format and specific arguments and here in this question we had to print the string with specific number of characters and in a format.

    • + 1 comment

      Can you please explain this part of the code:

      System.out.printf("%03d",x);

      It is fine that you mentioned it has 3 digits, but how do you let the system know, that it should print the number "0" to the left?

      • + 0 comments

        As far as I know we can print zeroes in front of a number for a specific length. Here I wrote "%03d" meaning the length of number will be three and we add zeroes to cover up the length. We can also have empty spaces on both sides by writing positive or negative number like we did in "%-15s". We can also add other characters like , or . and many more. You can check out string format to know more about it.