Contents

  1. ./ConsoleUsingConsoleDemo.java
  2. ./ConsoleUsingScannerDemo.java
  3. ./FileTest.java
  4. ./FinallyTest.java

./ConsoleUsingConsoleDemo.java 1/4

[
top][prev][next]
/**
 * 
 */
package examples;

import java.io.Console;

/**
 * A program that demonstrates reading in from the console, using calculating
 * the area of a rectangle as the example.
 * 
 * Does not work within an IDE directly--have to run from a terminal.
 * 
 * Note that this class does not have the error checking that
 * ConsoleUsingScannerDemo has.
 * 
 * @author Sara Sprenkle
 */
public class ConsoleUsingConsoleDemo {

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

		Console console = System.console();
		if (console == null) {
			System.err.println("No console.");
			System.exit(1);
		}

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

		// check for bad input, read in the integer representing the width
		String widthLine = console.readLine(widthPrompt);

		int width = Integer.parseInt(widthLine);

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

		// check for bad input, read in the integer representing the width
		String heightLine = console.readLine(heightPrompt);

		int height = Integer.parseInt(heightLine);

		/*
		 * scan.close();
		 */
		int area = height * width;

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

}

./ConsoleUsingScannerDemo.java 2/4

[
top][prev][next]
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);
	}

}

./FileTest.java 3/4

[
top][prev][next]
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Demonstrate using File objects and FileInputStreams in Java.
 * 
 * @author Sara Sprenkle
 * 
 */
public class FileTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// String basedir =
		// "/Users/sprenkle/Documents/WLU/CS209/";
		String basedir = ".";
		// create a file that represents the current directory
		// File f = new File(basedir + File.separator + "chicken.data");
		File f = new File("chicken.data");
		System.out.println("File is " + f.getAbsolutePath());
		try {
			
			FileInputStream fin = new FileInputStream(f);
			while (fin.available() > 0) {
				System.out.println(fin.read());
			}
			
			/* Consider how we'd write the code if we don't use the available() method:
			 * When would the loop stop?
			 * The loop would keep going, waiting for more input.  That could be valid code,
			 * but more often, you probably want to stop looping when you run out of stuff to read,
			 * like from a file.
			 */
			/*
			while( true ) {
				int input = fin.read();
				System.out.println(input);
			}
			*/
			fin.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		File notAFile = new File("/this/is/not/a/file");
		displayInfo(f);
		displayInfo(notAFile);

	}

	/**
	 * Displays info about the file
	 * @param myFile
	 */
	private static void displayInfo(File myFile) {
		System.out.println(myFile.getAbsolutePath() + " is a file: "
				+ myFile.isFile());
		System.out.println(myFile.getAbsolutePath() + " is a directory: "
				+ myFile.isDirectory());
	}

}

./FinallyTest.java 4/4

[
top][prev][next]
/**
 * Example using finally block
 * 
 * @author Sara Sprenkle
 */
public class FinallyTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			System.out.println("In try");
			//throw new NullPointerException();
		} catch (Exception e) {
			System.out.println("In Catch");
		} finally {
			System.out.println("In Finally");
		}
	}

}


Generated by GNU Enscript 1.6.6.