Formatted Print in Java

Development & UX Researches
2 min readJul 20, 2020

--

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

--

--

Development & UX Researches
Development & UX Researches

Written by Development & UX Researches

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

No responses yet