//******************************************************************** // Zero.java Author: Lewis and Loftus // // Demonstrates an uncaught exception. //******************************************************************** public class Zero { //----------------------------------------------------------------- // Deliberately divides by zero to produce an exception. //----------------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } } //******************************************************************** // Zero2.java // // Demonstrates an uncaught exception with a longer call stack trace. //******************************************************************** public class Zero2 { //----------------------------------------------------------------- // Deliberately divides by zero to produce an exception. //----------------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; illegal(numerator, denominator); System.out.println ("This text will not be printed either."); } public static void illegal (int num, int den) { System.out.println (num / den); System.out.println ("This text will not be printed."); } } //******************************************************************** // ProductCodes.java // // Demonstrates the use of a try-catch block. //******************************************************************** import java.util.*; public class ProductCodes { //----------------------------------------------------------------- // Counts the number of product codes (???0000??A...) that are // entered with a zone of R and and district greater than 2000. //----------------------------------------------------------------- public static void main (String[] args) { String code; char zone; int district, valid = 0, banned = 0; Scanner scan = new Scanner(System.in); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); while (!code.equals ("XXX")) { try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); } System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); } System.out.println ("# of valid codes entered: " + valid); System.out.println ("# of banned codes entered: " + banned); } } //******************************************************************** // WildernessIndex.java // // Demonstrates exception propagation. //******************************************************************** public class WildernessIndex { static public void main (String[] args) { WorldZoom wildIndex = new WorldZoom(); System.out.println("Picking a country..."); wildIndex.theUS(); System.out.println("\nPicking another country..."); wildIndex.canada(); System.out.println("\nDone."); } } //******************************************************************** // WorldZoom.java // // Demonstrates exception propagation. //******************************************************************** class WorldZoom { //----------------------------------------------------------------- // Catches and handles the exception that is thrown in montreal. //----------------------------------------------------------------- public void canada() { System.out.println("Zooming in to Canada."); try { quebec(); } catch (ArithmeticException problem) { System.out.println (); System.out.println ("The exception message is: " + problem.getMessage()); System.out.println (); System.out.println ("The call stack trace:"); problem.printStackTrace(); System.out.println (); } System.out.println("Zooming out of Canada."); } //----------------------------------------------------------------- // Serves as an intermediate level. The exception propagates // through this method back to canada. //----------------------------------------------------------------- public void quebec() { System.out.println("Zooming in to Quebec."); montreal (); System.out.println("Zooming out of quebec."); } //----------------------------------------------------------------- // Performs a calculation to produce an exception. It is not // caught and handled at this level. //----------------------------------------------------------------- public void montreal() { int numPeople = 3000000, numBears = 0; System.out.println("Zooming in to Montreal."); int result = numPeople / numBears; System.out.println("The wilderness index is: " + result); System.out.println("Zooming out of Montreal."); } public void theUS() { System.out.println("Zooming in to the US."); try { alaska(); } catch (ArithmeticException problem) { System.out.println (); System.out.println ("The exception message is: " + problem.getMessage()); System.out.println (); System.out.println ("The call stack trace:"); problem.printStackTrace(); System.out.println (); } System.out.println("Zooming out of the US."); } public void alaska() { System.out.println("Zooming in to Alaska."); kodiak (); System.out.println("Zooming out of Alaska."); } public void kodiak() { int numPeople = 13000, numBears = 3000; System.out.println("Zooming in to kodiak island."); int result = numPeople / numBears; System.out.println("The wilderness index is: " + result); System.out.println("Zooming out of kodiak island."); } } //******************************************************************** // Ball.java // // Testing exception hierarchies //******************************************************************** class Ball extends Exception { } //******************************************************************** // BaseBall.java // // Testing exception hierarchies //******************************************************************** class BaseBall extends Ball { } //******************************************************************** // FootBall.java // // Testing exception hierarchies //******************************************************************** class FootBall extends Ball { } //******************************************************************** // LetsPlayCatch.java // // Testing exception hierarchies //******************************************************************** class LetsPlayCatch { private static FootBall ball = new FootBall(); //or Ball or BaseBall public static void main (String[] args) { int i = 0; while (i<100) { try { if (++i % 3 == 0) { System.out.println("Going for a long one..."); throw ball; } System.out.println("Try #" + i); } catch (Ball b) // or Exception or Throwable { System.out.println("uummpphhh...I got it! I got it!"); } } } } //******************************************************************** // Professor.java // // Represents an Professor, which is a type of prey //******************************************************************** public class Professor extends Prey { public Professor(String name, int weight) { super(name,weight); } } //******************************************************************** // PredatorsAreNotEatenException.java // // Represents an exceptional condition in which we are trying to // eat a Predator //******************************************************************** public class PredatorsAreNotEatenException extends Exception { //----------------------------------------------------------------- // Sets up the exception object with a particular message. //----------------------------------------------------------------- public PredatorsAreNotEatenException (String message) { super (message); } } //******************************************************************** // YouShouldNotTryToHaveYourProfessorEatenException.java // // Represents an exceptional condition in which we are trying to // eat a Professor //******************************************************************** public class YouShouldNotTryToHaveYourProfessorEatenException extends Exception { //----------------------------------------------------------------- // Sets up the exception object with a predefined message. //----------------------------------------------------------------- public YouShouldNotTryToHaveYourProfessorEatenException () { super ("Having your professor eaten will not help you pass the final."); } } //******************************************************************** // WhoYouShouldAndShouldNotEat.java // // Demonstrates the ability to define an exception via inheritance. //******************************************************************** import java.util.Scanner; public class WhoYouShouldAndShouldNotEat { //----------------------------------------------------------------- // Creates a checked exception and possibly throws it. //----------------------------------------------------------------- public static void main (String[] args) throws YouShouldNotTryToHaveYourProfessorEatenException, PredatorsAreNotEatenException { PredatorsAreNotEatenException tooMuchRisk = new PredatorsAreNotEatenException ("We won't allow it, it's too dangerous."); Scanner scan = new Scanner(System.in); int value; Animal [] whoEatsWho = new Animal [2]; //first one is eater, second one is eaten String [] message = {"Who do you want feed? ","Who do you want to be eaten? "}; for (int i = 0; i< whoEatsWho.length; i++) { System.out.println ("\t1. Simba"); System.out.println ("\t2. Mamba"); System.out.println ("\t3. Chui"); System.out.println ("\t4. Fisi"); System.out.println ("\t5. Digidigi"); System.out.println ("\t6. Twiga"); System.out.println ("\t7. Yannick"); System.out.println ("\t8. Nobody"); System.out.print (message[i]); value = scan.nextInt(); switch (value) { case 1: whoEatsWho[i] = new Lion("Simba", 220, "Wildebeests, zebras, buffaloes, young elephants, rhinos, hippos, giraffes, warthogs, antelopes, hyenas, humans and even crocodiles",15.0); break; case 2: whoEatsWho[i] = new Predator ("Mamba",400,"Fish, antelopes, buffaloes, Wildebeests, zebras, and humans", 30.0); break; case 3: whoEatsWho[i] = new Predator ("Chui",60,"Baboons, zebras, hares, warthogs, antelopes and humans",15.0); break; case 4: whoEatsWho[i] = new Hyena ("Fisi", 80, "Wildebeests, humans, zebras, buffaloes, warthogs, antelopes, cheetahs, hyenas and almost anything", 8.0, true); break; case 5: whoEatsWho[i] = new Prey ("Digidigi",4); break; case 6: whoEatsWho[i] = new Prey ("Twiga",1350); break; case 7: whoEatsWho[i] = new Professor("Yannick",66); break; } if (whoEatsWho[i] != null) System.out.println (whoEatsWho[i] + "\n-------------------------"); } if (whoEatsWho[1] instanceof Professor) //The only Preys we don't want to eat are Professors throw new YouShouldNotTryToHaveYourProfessorEatenException(); else if (whoEatsWho[1] instanceof Predator) //We don't want to eat ANY Predators throw tooMuchRisk; try { double amount = whoEatsWho[0].feed((Prey)whoEatsWho[1]); // polymorphic System.out.println ("Fed: " + amount); } catch (NullPointerException problem) { System.out.println ("You shouldn't be afraid to have somebody eat somebody."); } } } //******************************************************************** // countries.dat //******************************************************************** Canada;31147000;9970610 China;1277558000;9572900 Namibia;1726000;824300 Peru;25662000;1285200 Spain;39630000;504750 //******************************************************************** // MyWorld.java // // Demonstrates the use of a text file input stream. //******************************************************************** import java.util.*; import java.io.*; public class MyWorld { //----------------------------------------------------------------- // Reads data about a list of countries from an input file, // creating an array of Country objects, then prints them. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX = 200; Country[] myWorld = new Country[MAX]; String line, name, fileName="countries.dat"; int count = 0; long population, area; try { Scanner fileScan = new Scanner (new File(fileName)); while (fileScan.hasNext()) { line = fileScan.nextLine(); Scanner lineScan = new Scanner(line).useDelimiter(";"); try { name = lineScan.next(); population = lineScan.nextLong(); area = lineScan.nextLong(); myWorld[count++] = new Country (name, population, area); } catch (NoSuchElementException exception) { System.out.println ("Error in input. Line ignored:"); System.out.println (line); } } for (int i = 0; i < count; i++) System.out.println (myWorld[i]); } catch (FileNotFoundException exception) { System.out.println ("The file " + fileName + " was not found."); } } } //******************************************************************** // Country.java // // Represents an country in the world. //******************************************************************** import java.io.*; public class Country { private String name; private long population; // number of people private long area; // geographical area //----------------------------------------------------------------- // Sets up this country with the specified information. //----------------------------------------------------------------- public Country (String countryName, long numPeople, long size) { name = countryName; population = numPeople; area = size; } //----------------------------------------------------------------- // Returns information about this country as a string. //----------------------------------------------------------------- public String toString() { return name + ": " + population + " people on " + area + " sqKms is " + (population / area) + " people per sqkm"; } //----------------------------------------------------------------- // Append country information to file fileName. // Pass checked IOException handling to calling method. //----------------------------------------------------------------- public void addToFile(String fileName) throws IOException { FileWriter fw = new FileWriter (fileName,true); //true for appending BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); outFile.println (name + ";" + population + ";" + area); outFile.close(); } }