Contents

  1. ./AnotherFinallyTest.java
  2. ./Birthday.java
  3. ./FileTest.java
  4. ./FinallyTest.java

./AnotherFinallyTest.java 1/4

[
top][prev][next]
import java.io.IOException;
import java.util.Random;

/**
 * An example with the finally clause, to show why it's necessary. This is as
 * opposed to just having code after the try/catch
 * 
 * @author CSCI209
 */
public class AnotherFinallyTest {

	private static final Random randomNumberGenerator = new Random();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		handlesExceptions();
	}

	public static void handlesExceptions() {
		try {
			throwsExceptions();
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Problem happened, but I caught it!");
		} finally {
			System.out.println("In Finally");
		}

		// this only executes if the above code "went okay"
		// i.e., only if either the try executed successfully or
		// the catch executed.
		// If something "escaped" the try/catch, then we won't reach here.
		System.out.println("After the try/catch");

	}

	public static void throwsExceptions() {
		int whichException = randomNumberGenerator.nextInt(3);

		switch (whichException) {
		case 0:
			System.out.println("ArrayIndexOutOfBoundsException - will be caught/handled");
			throw new ArrayIndexOutOfBoundsException();
		case 1:
			System.out.println("IllegalArgumentException - won't be caught/handled");
			throw new IllegalArgumentException();
		default:
			System.out.println("No problems!!");
		}

	}
}

./Birthday.java 2/4

[
top][prev][next]
import java.util.GregorianCalendar;

/**
 * Pedagogical purpose: demonstrates use of throwing
 * IllegalArgumentExceptions to prevent errors.
 *
 * @author CSCI209
 */
public class Birthday {
	private int day;
	private int month;

	private static final int[] DAYS_IN_MONTH = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	
	private static final String[] MONTHS = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	
	/**
	 * Creates a new Birthday object with the given month and day
	 * 
	 * @param month the integer month of the birthday, e.g., January is 1, February is 2
	 * @param day the day of the month of the birthday
	 */
	public Birthday(int month, int day) {
		setBirthday(month, day);
	}

	/**
	 * Returns a String representation of the Birthday as "month/day"
	 * 
	 * @return the Birthday as a string in the format "month/day"
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(month);
		builder.append("/");
		builder.append(day);
		return builder.toString();
	}

	/**
	 * Rather than setting the month and the day in separate methods, 
	 * this is a better way to implement setting the month and the day. Why?
	 * 
	 * @param month the integer month of the birthday, e.g., January is 1, February is 2 (between 1-12)
	 * @param day the day of the month of the birthday (between 1 and the number of possible days in the month)
	 * @throws IllegalArgumentException if month or day are invalid
	 */
	public void setBirthday(int month, int day) {
		boolean error = false;
		StringBuilder errorMessage = new StringBuilder();
		if( month < 1 || month > 12) {
			error = true;
			errorMessage.append("month must be between 1 and 12");
		}
		if( day < 1 || day > 31 ) {
			if( error ) {
				errorMessage.append(" and ");
			}
			errorMessage.append("day must be between 1 and 31\n");
			error = true;
		}
		// don't need to check if there was a problem with the month
		else if( !error && day > DAYS_IN_MONTH[month - 1] ) { 
			error = true;
			errorMessage.append( MONTHS[month-1] + " has only " + DAYS_IN_MONTH[month-1] + " days.");
		}
		
		if( error ) {
			throw new IllegalArgumentException(errorMessage.toString());
		}
		
		// only set the month and day after we know that 
		// the month and day are valid.
		this.month = month;
		this.day = day;
	}
	
	/**
	 * Returns the day of the month of the Birthday
	 * @return the day of the month of the Birthday
	 */
	public final int getDay() {
		return day;
	}

	/**
	 * Returns the month of the Birthday, where 1 is January, 2 is February, ...
	 * @return the month of the Birthday, where 1 is January, 2 is February, ...
	 */
	public final int getMonth() {
		return month;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Birthday b = new Birthday(1, 1);
		System.out.println("New Year's Baby: " + b);
		Birthday leapYearBaby = new Birthday(2, 29);
		System.out.println("Leap Year Baby: " + leapYearBaby);
		
		b.setBirthday(4, 30); // this should work
		System.out.println("End of April birthday: " + b);

		/* 
		 Test calling the method with the exceptions:
		 Each of the statements below, separately, will throw an exception.  
		 Comment out the others to see what one of them does.
		 (Wouldn't it be great if we had a better way to test exceptions?) 
		*/
		b.setBirthday(1,32); 
		b.setBirthday(2,30); 
		b.setBirthday(0, 32);
		Birthday b2 = new Birthday(1, 32);
		
	}

}

./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 CSCI209
 * 
 */
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 (if it's a file and if it's a directory) about the given file
	 * 
	 * @param myFile the file to display information about
	 */
	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]
import java.io.IOException;

/**
 * Example using finally block.
 * Enables playing with try/catch/finally executions--
 * just uncomment/comment out the thrown exceptions
 * 
 * @author CSCI209
 */
public class FinallyTest {

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

}


Generated by GNU Enscript 1.6.5.90.