Output Sent to a File

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Yes. It is a little awkward, however, because the user prompts as well as the computed answer will be sent to the output text file.

Output Sent to a File

Here is an example of redirecting the output of this file. Notice that the user does not see any prompts because they have been sent to the output file:

C:/users/default/JavaLessons>java Discount > discount.out

100
20

C:/users/default/JavaLessons>type discount.out
Enter list price in cents:
Enter discount in percent:
Discount Price: 80

C:/users/default/JavaLessons>

This is somewhat awkward: the user sees half the dialog, and the other half goes to the file. It would be better if both the user and the file got the complete dialog. The standard error output stream can be used for this. Characters sent to standard error appear on the monitor (even when output is redirected to a disk file). Do this by using System.err.println() for characters to go to the monitor and System.out.println() for characters to go to the file:

import java.util.Scanner;
class DiscountErr
{
  public static void main ( String[] args ) 
  {
    int listPrice;
    int discount;
    int discountPrice;

    Scanner scan = new Scanner( System.in );

    System.err.print("Enter list price in cents: ");     // print prompt on monitor
    listPrice = scan.nextInt();
    System.out.println("Price in cents: " + listPrice ); // echo input to disk

    System.err.print("Enter discount in percent: "); // print prompt on monitor
    discount = scan.nextInt();
    System.out.println("Discount: " + discount );    // echo input to disk

    discountPrice = listPrice - (listPrice*discount)/100 ;

    System.out.println( "Discount Price: " + discountPrice );  // send to disk file
    System.err.println( "Discount Price: " + discountPrice );  // send to monitor
  }
}

QUESTION 12:

Can the user pick any file name for the redirected output?