Java Formatter set a minimum field width

Introduction

An integer between the &%& sign and the format conversion code is the minimum field-width specifier.

Java Formatter will pad the output with spaces to ensure that it reaches the minimum length.

If the string or number is longer than that minimum, it will be printed in full.

The default padding is done with spaces.

To pad with 0's, place a 0 before the field-width specifier.

For example, %05d will pad a number of less than five digits with 0's so that its total length is five.

The field-width specifier can be used with all format specifiers except %n.

The following program demonstrates the minimum field-width specifier by applying it to the %f conversion:

// Demonstrate a field-width specifier. 
import java.util.Formatter; 
 
public class Main { 
  public static void main(String args[]) { 
    Formatter fmt = new Formatter(); 
 
    fmt.format("|%f|%n|%12f|%n|%012f|", 
               110.12345, 110.12345, 110.12345); 
 
    System.out.println(fmt); /*w  w w . jav  a2 s  . c  om*/

    fmt.close(); 
  } 
}

The minimum field-width modifier can produce tables and line up the columns.

For example, the next program produces a table of squares and cubes for the numbers between 1 and 10:


// Create a table of squares and cubes. 
import java.util.Formatter;

public class Main {
  public static void main(String args[]) {
    Formatter fmt;/*from ww  w  .j  av  a2 s. c  o  m*/

    for (int i = 1; i <= 10; i++) {
      fmt = new Formatter();

      fmt.format("%4d %4d %4d", i, i * i, i * i * i);
      System.out.println(fmt);
      fmt.close();
    }
  }
}

The following code displays the result in a table.

public class Main {
   public static void main(String[] args) {
      // Display the header of the table
      System.out.printf("%-10s%-10s%-10s%-10s%-10s\n", "Degrees", "Radians", "Sine", "Cosine", "Tangent");

      // Display values for 30 degrees
      int degrees = 30;
      double radians = Math.toRadians(degrees);
      System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n", degrees, radians, Math.sin(radians), Math.cos(radians),
            Math.tan(radians));/*from   w w w .  j av a2s.c om*/

      // Display values for 60 degrees
      degrees = 60;
      radians = Math.toRadians(degrees);
      System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n", degrees, radians, Math.sin(radians), Math.cos(radians),
            Math.tan(radians));
   }
}



PreviousNext

Related