// see pg 85 and chap14.txt // Some exceptions are CHECKED by the compiler. But, why? how? // Some methods from Java API can easily make "mistakes" // as in wrong input, doing illegal math, etc. // So, many of these methods cause exceptions. // In the hopes of creating code that won't crash, Java // forces the programmer to handle these exceptions by making // many of them CHECKED. If the compiler spots a method you have not // provided checking using throws or catch, the compiler will complain. import java.io.*; // need for I/O routines below public class except4 { // The following code will contain readline() which MIGHT issue // an IOException. Two ways to handle exception: // 1st way: use a catch // 2nd way: have main "throw" the exception like throwing a // "hot potato" out of the program // The "throws IOException" is the 2nd way // I left it out to show you how the compiler will gripe. /* The Excetption from the compiler: except4.java:35: Exception java.io.IOException must be caught, or it must be declared in the throws clause of this method. String temp = stdin.readLine(); ^ 1 error */ public static void main(String args[]) { // fix the mistake by saying: // public static void main(String args[]) throws IOException { // Alternative solution to HW1 follows. // initialize Text object in to read from standard input. BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); // Read and write some numbers and strings System.out.println("Please enter an integer: "); // Read integer String temp = stdin.readLine(); int k = Integer.parseInt(temp); // Perform algorithm while ( k > 1 ) if ( (k % 2 ) == 0) { // test if k is even k = k / 2; System.out.println(k + " after dividing by 2"); } else { k = 3 * k + 1; System.out.println(k + " after multiplying by 3 and adding 1"); } System.out.println("Done!"); } }