package examples;

import java.util.Scanner;

/**
 * A program that demonstrates reading in from the console, using calculating
 * the area of a rectangle as the example.
 * 
 * @author Sara Sprenkle
 */
public class ConsoleUsingScannerDemo {

	/**
	 * @param args
	 *            not used in this program
	 */
	public static void main(String[] args) {
		System.out
				.println("This program calculates the area of a rectangle.\n");

		// open the Scanner on the console input, System.in
		Scanner scan = new Scanner(System.in);

		// Comment this out and enter the text "6 7", for example
		scan.useDelimiter("\n"); // breaks up by lines, useful for
									// console I/O

		// prompt the user for the width
		String widthPrompt = "Please enter the width of a rectangle (as an integer): ";

		promptAndHandleIntegerInput(scan, widthPrompt);

		int width = scan.nextInt();
		scan.nextLine(); // eat the new line that the user entered after the
							// width was entered (why is there another new
							// line?)

		// prompt the user for the height
		String heightPrompt = "Please enter the height of a rectangle (as an integer): ";
		promptAndHandleIntegerInput(scan, heightPrompt);
		int length = scan.nextInt();
		// don't need to worry about eating the new line because not getting any
		// more user input after this.
		scan.close();

		int area = length * width;

		System.out.println("The area of your rectangle is " + area + ".");
	}

	/**
	 * Handles prompting for integer input and verifying that we get an integer
	 * back.
	 * 
	 * @param scan
	 * @param prompt
	 *            the prompt used to request the input
	 */
	private static void promptAndHandleIntegerInput(Scanner scan, String prompt) {
		System.out.print(prompt);

		// check for bad input, read in the integer representing the width
		while (!scan.hasNextInt()) {
			handleBadInput(scan, prompt);
		}
	}

	/**
	 * When the user enters bad input, remove the rest of what's on the line
	 * from the scanner and print out an error message and a reminder of what
	 * the input should look like.
	 * 
	 * @param scan
	 *            where the bad input is coming from
	 * @param prompt
	 *            a reminder of what we're looking for
	 */
	public static void handleBadInput(Scanner scan, String prompt) {
		// read the bad input (up to the \n, which is what the user
		// entered to trigger reading the input)
		if (scan.hasNextLine()) {
			scan.nextLine();
		}

		// give an error message and then repeat what we want
		System.out.println("Incorrect input.");
		System.out.print(prompt);
	}

}
