Use a Formatter object to format 20 random values of type double between –50 and +50 and output the entire set of 20 in a single call of System.out.print() or System.out.println().
Output of Above Java Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.Formatter; import static java.lang.Math.random; public class FormatToString { public static void main(String[] args) { double [] data = new double [ 20 ]; for ( int i = 0 ; i < data.length ; ++i) { data[i] = 100.0 *random() - 50.0 ; } StringBuilder buf = new StringBuilder(); // Buffer to hold output Formatter formatter = new Formatter(buf); // Formatter to format data into buf int i = 0 ; for ( double x : data) { formatter.format( "%4d)%+7.2f" , ++i, x); if (i% 5 == 0 ) { formatter.format( "%n" ); } } System.out.println(buf); // Output all the values in one go } } |
Output of Above Java Program
1) +46.53 2) -5.14 3) -3.81 4) -45.54 5) +32.27 6) -23.71 7) +47.19 8) +44.52 9) -19.52 10) -35.47 11) -9.32 12) -28.05 13) +44.03 14) -46.65 15) -5.68 16) +46.42 17) -8.72 18) -13.47 19) -44.96 20) +46.57