Posts Tagged Formatter class

Demonstrates the PRECISION modifier in Formatter Class.

A Precision modifier can be applied to any format specifier. It follows the minimum field width specifier(if it is there) and consists of a period followed by an integer.  The default precision is 6. For example, %10.4f  prints a number at least ten character wide with four decimal places. In case of String, it specifies the maximum field width. For example, %5.7s prints a string at least  five and not exceeding  seven characters long.

import java.util.*;

class FormatterExample{

public static void main(String a[]){

Formatter fm= new Formatter();

//Format 4 decimal places

fm.format(" %.4f",123.1234567);

System.out.println(fm);

//Format to 2 decimal placesin a 16 cheracter field

fm= new Formatter();

fm.format(" %16.2e",123.1234567);

System.out.println(fm);

//print at most 15 characters  in a string

fm= new Formatter();

fm.format(" %.15s","I love java.");

System.out.println(fm);

}

}

, ,

3 Comments

Creates a table of squares and cubes using minimum field width using Formatter Class.

This example demonstrates the use of formatter class and also using minimum field width.

Output::

1      1       1

2      4      8

3       9   27

.         .       .

.         .       .

import java.util.*;

class FormatterExample{

public static void main(String a[]){

Formatter fm= new Formatter();

for(int j=1; j<=5; j++){

fm.format("%5d %5d %5d", i, i*i, i*i*i);

System.out.println(fm);

}

}
}

, , , , ,

2 Comments

Demonstrates a field width specifier in Formatter Class.

Output::

10.123450

10.123450
00010.123450

import java.util.*;

class FormatterExample{

public static void main(String a[]){

Formatter fm= new Formatter();

fm.format("%f %n %12f %n %012f", 10.12345, 10.12345, 10.12345);

System.out.println(fm);

}

}

, ,

No Comments

Demonstrates the %n and %% format specifiers.

This example demonstrates the use of  format specifiers %n( new line) and %%(to print ‘%’ character) in java using Formatter Class.

import java.util.*;

class FormatterExample{

public static void main(String a[]){

Formatter fm= new Formatter();

fm.format("Download %n is %d%% completed",45);

}

}

, , , , ,

No Comments

Formatter Class- Demonstrates the use of %g format specifier.

This example demonstrates the use of  %g format specifier.

import java.util.*

class FormaterExample {

public static void main(String a[]){

Formatter fm=new Formatter();

for(double i=100; i<1.0e+10; i*=100){

fm.format("%g",i);

System.out.println(fm);

}

}
}

, , ,

1 Comment

Formatter Class-Simple example.

A simple example to understand concept of Formatter class.

import java.util.*;

class FormatterExample{

public static void mainn( String a[]){

Formatter fm= new Formattre();

fm.format("Java %s easy %d %f", "is so", 1,91.3);

System.out.println(fm);

}
}

,

No Comments