Printing the texts in table format in Java
In this tutorial, we are learning how to print the texts in table format in the console in Java. By using the String.format function and printf we can print the content in a format.
Also read:
how to print percentage in java using string.format
Formatting the output using String.format function
public class PrintingInTableFormat { public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter employee id,name and salary"); while(sc.hasNext()) { int id=sc.nextInt(); String name=sc.next(); int salary=sc.nextInt(); String s=String.format("%d%15s%6d",id,name,salary); System.out.println(s); } } }
The output looks like this:
Enter employee id,name and salary 131 sathwik 50000 168 siddharath 59000 199 karthik 6000 131 sathwik 50000 168 siddharath 59000 199 karthik 6000
Using System.out.printf for formatting
printf has two parameters.
public PrintStream printf(String format,Object args)
- format is for formatting the string
- args is used for specifying the number of arguments
The format specifiers are same as String.format.
Formatting the output using printf
public class abcde { public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter employee id,name and salary"); while(sc.hasNext()) { int id=sc.nextInt(); String name=sc.next(); int salary=sc.nextInt(); System.out.printf("%d%15s%6d\n",id,name,salary); } } }
The output looks like this:
Enter employee id,name and salary 131 sathwik 50000 168 siddharath 59000 199 karthik 6000 131 sathwik 50000 168 siddharath 59000 199 karthik 6000
Leave a Reply