Formatting Output w/ printf() Method

PHOTO EMBED

Sun Jan 16 2022 06:50:27 GMT+0000 (UTC)

Saved by @mikemcnik #java

/*
printf(String format, [value,...])
Format: %-,X.Yf

Always starts with %
-Causes the value to be left justified.  Otherwise it is right justified
A comma causes commas to be displated in the printed number
X = field width
Y is number of digits after the decimal point
f is format type: d = integer (int), f = floating point number (double), s = string
*/

//EXAMPLE
int x = 123, y = 46789;
double a = 3.14159265, b = 2.7182818;
String first = "Wilma", last = "Flintstone";
System.out.printf("%6d %-,d\n", x, y); //Punctuation counts towards spaces
System.out.printf("%5.2f %-7.4\n", a, b);
System.out.printf("first = [%s] last = [%12s]\n", first, last);

/*
Prints as :
___123 456,789_
_3.14 2.7183_
First = [Wilma] last = [__Flinststone]
*/


//Example
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/* 
Contents of scores-in.txt:
80 90 70
40 60 80
100 93 87
*/

public class ExamAvg {
  public static void main(String[] args) throws FileNotFoundException {
    //open "scores-in.txt" fore reading
    scanner in = new Scanner(new FIle("scores-in.txt"));
    //open "scores-out.txt" for writing
    PrintWriter out = newe PrintWriter(new File("scores-out.txt"));
    //Print the column headers
    out.println("Exam 1  Exam 2  Exam 3  Exam Avg");
    out.println("------  ------  ------  --------");
    //Read teh exam scores form "score-in.txt", calculate the exam average, and print the formatted output to the output fle
    while(in.hasNext()){
      int e1 = in.nextInt();
      int e2 = in.nextint();
      int e3 = in.nextint();
      double avg = (e1 + e2 + e3) / 3.0;
      out.printf("%6d %6d %6d %8.1f\n", e1, e2, e3, avg);
    }
    //Close the input file
    in.close;
    //close the output file
    out.close;
  }
}




content_copyCOPY

Printing with formatting.