Formatted Print in Java

Formatting, Credits: Lynda

Once we ask the ‘system’ to ‘output’ the data, generally System.out.println() is used. What if you would like to format the output of the program? How to format the program or make it more dynamic?

Let’s assume you are using the Scanner util class of java, and there are many different types of input each time. Once you asked the customer to enter her name, age, sex, and height. Finally she can see what she had entered at the end.

public static void intro(){Scanner scanner = new Scanner(System.in);String name = scanner.nextLine();int age = scanner.nextInt();char sex = scanner.next().charAt(0);float height = scanner.nextFloat();System.out.printf(“\n Name is: %s \n Age is: %d \n Sex is: %c \n Height is: %.2f “, name, age, sex, height);}

Output:

Name is: JessicaAge is: 35Sex is: MHeight is: 5.70

In summary: The percent sign with the d,c,f,s letters, we can create more dynamic programs. Just we need to make sure we are using the printf() method with the correct format specifier!

Formatter Specifiers, Credits: Sdet & Updates

*Warning: Do not fall into the mistake of using %d for double but use %f instead. Make sure to pay attention the correct specifier! Otherwise, you will catch Exception in thread “main” java.util.IllegalFormatConversionException: d != java.lang.Double

--

--

--

A self-learner in the programming and automation industry. Keep yourself updated in this journey together ;)

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

My Tech Journey with Goitom Seyoum, Staff Software Engineer at Google

Sukhavati POC module accepted by the Web3 Foundation

Right way of coding with “using”

3 central design considerations for SaaS

Why Software Testing is hardest job

Marge-bot for GitLab keeps master always green

Baidu spent six years building the metaverse

Wait, what is my fleet doing?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sdet & Updates

Sdet & Updates

A self-learner in the programming and automation industry. Keep yourself updated in this journey together ;)

More from Medium

Singleton(s) in Java

Numbering System edge cases of java

Annotations In Java

Classes and Objects in Java