Formatting

Return within a line: “\r” or “\n” ex:

  • \n // New line.  Go to beginning of next line
  • \r //Carriage return.  Go to beginning of current line.
System.out.println("This will be on line 1" + "\rThis will be on line 2" + "\nThis will be on line 3");

Tab

+ "\t"
System.out.print( 1 + r.nextInt(100) + "\t" );
System.out.print( 1 + r.nextInt(100) + "\t" );

Will return on same line with tab after each print

printf

  • System.out.printf can have any number of arguments
    • The first argument is always a format string that contains one or more format specifiers for the remaining arguments
    • All the arguments except the first are values to be output to the screen
double price = 19.8;
System.out.print("$");
System.out.printf("%6.2f", price);
System.out.println(" each");

will output the line

$ 19.80 each

The format string "%6.2f" indicates the following:

End any text to be output and start the format specifier (%)
–Display up  to 6 right-justified characters, pad fewer than six characters on the left with blank spaces (i.e., field width is 6)
–Display exactly 2 digits after the decimal point (.2)
–Display a floating point number, and end the format specifier (i.e., the conversion character is f)
String -> %s
Character -> %c