Coders Packet

How to format the Output in Java

By Kashish Naresh Dhoot

The purpose of this project is to explain to you the use of the "System.out.printf("%-15s%03d%n",s1,x)" method to print the formatted output in Java.

Formatting the Output in Java

Here in this project, we have to format the input to get the specified output.

We will be using:- "System.out.printf("%-15s%03d%n",s1,x);" .

Here:- '%' means what follows with an argument that will be formatted.

           '-' is used for left-alignment.

           '15' is used to fill the string up to length 15 by adding extra spaces.

          's' means the string is formatted.

          '0' means to fill the character by adding extra zeros if needed.

          '3' is used to fill the character 0 as many times as needed to make the integer 3 digits.

          'd' means an integer is formatted.

To format the string s1:- "%-15s" is used.

To format an integer x:- "%03d" is used.

 

import java.util.Scanner;
public class OutputFormatting {

    public static void main(String[] args) 
    {
            Scanner sc=new Scanner(System.in);
            
            for(int i=0;i<3;i++)
            {
                String s1=sc.next();
                int x=sc.nextInt();
                System.out.println("================================");
                System.out.printf("%-15s%03d%n",s1,x);
                
            }
            System.out.println("================================");

    }
}

 

Output:

output of the code

Download project

Reviews Report

Submitted by Kashish Naresh Dhoot (Kashish1104)

Download packets of source code on Coders Packet