dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jan 28, 2019

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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.next().toString(), scanner.hasNextBoolean() ));
      }

      //Closing the Scanner
      scanner.close();
   }
}

/*

Expected output:

[root@mypc]# java StringFormatter
Hi        : false
there,    : false
is        : false
it        : true
true      : false
that      : false
you       : false
are       : false
coming    : false
home      : false
today?    : false
*/
M S Sridhar
 
Thanks for your registration, follow us on our social networks to keep up-to-date