Formatting Output in Java

Formatting Output in Java

Proper formatting of output is essential. There are times when the details presented are not formatted.

The code snippet below displays details in a formatted manner that is a better presentation.

import java.util.*;public class StringFormatter {   public static void main(String args[])   {      StringFormatter stringFormatter = new StringFormatter();      stringFormatter.proceed();   }   final String stringSentence = "Hi there, is it true that you are coming home today?";      private void proceed()   {      //Creating a Scanner with the string stringSentence      Scanner scanner = new Scanner(stringSentence);      //Scanning the string       while (scanner.hasNext()) {         //Formatting the string. The first string will have 10 character spacing, this can be adjusted as needed.          //The option -10, 10 will add spaces leading and trailing respectively.         System.out.println(String.format("%-10s: %s" ,, scanner.hasNextBoolean() ));      }      //Closing the Scanner      scanner.close();   }}/*

Expected output:

[root@mypc]# java StringFormatterHi        : falsethere,    : falseis        : falseit        : truetrue      : falsethat      : falseyou       : falseare       : falsecoming    : falsehome      : falsetoday?    : false*/


Share the Post: