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

Introduction to Spring Boot

Frontend Technologies-Intro!

Install Jenkins on Kubernetes on MacOS (Monterey)

Agile World S2 E5 Sabrina C E Bruce and Karl A L Smith talk with Mark Walsh about Agile

Little Kidogo Sprint Retro Report #3

Why Learn Python in 2021

AWS Amplify Resources

A silhouette of a woman jumping for joy

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

Useless Java: Day 4

Anonymous/Unnamed code blocks in Java

Springboot annotations @BehindTheSeen(Scene)

Classes and Objects in Java