Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lab 8 Task 1: Write the following program to understand re-throwing exceptions Calculator.java import java.util.Scanner; public class Calculator { private double result; private double precision = 0.0001; // Numbers this close to zero are // treated as if equal to zero. public static void main(String[] args) { Calculator clerk = new Calculator( ); try { System.out.println("Calculator is on."); System.out.print("Format of each line: "); System.out.println("operator space number"); System.out.println("For example: + 3"); System.out.println("To end, enter the letter e."); clerk.doCalculation(); } catch(UnknownOpException e) { clerk.handleUnknownOpException(e); } catch(DivideByZeroException e) { clerk.handleDivideByZeroException(e); } System.out.println("The final result is " + clerk.getResult( )); System.out.println("Calculator program ending."); } public Calculator( ) { result = 0; } 1 public void reset( ) { result = 0; } public void setResult(double newResult) { result = newResult; } public double getResult( ) { return result; } /** The heart of a calculator. This does not give instructions. Input errors throw exceptions. */ public void doCalculation( ) throws DivideByZeroException, UnknownOpException { Scanner keyboard = new Scanner(System.in); boolean done = false; result = 0; System.out.println("result = " + result); while (!done) { char nextOp = (keyboard.next( )).charAt(0); if ((nextOp == 'e') || (nextOp == 'E')) done = true; else { double nextNumber = keyboard.nextDouble( ); result = evaluate(nextOp, result, nextNumber); System.out.println("result " + nextOp + " " + nextNumber + " = " + result); System.out.println("updated result = " + result); } } } 2 /** Returns n1 op n2, provided op is one of '+', '-', '*',or '/'. Any other value of op throws UnknownOpException. */ public double evaluate(char op, double n1, double n2) throws DivideByZeroException, UnknownOpException { double answer; switch (op) { case '+': answer = n1 + n2; break; case '-': answer = n1 - n2; break; case '*': answer = n1 * n2; break; case '/': if ((-precision < n2) && (n2 < precision)) throw new DivideByZeroException( ); answer = n1 / n2; break; default: throw new UnknownOpException(op); } return answer; } public void handleDivideByZeroException(DivideByZeroException e) { System.out.println("Dividing by zero."); System.out.println("Program aborted"); System.exit(0); } public void handleUnknownOpException(UnknownOpException e) { System.out.println(e.getMessage( )); 3 System.out.println("Try again from the beginning:"); try { System.out.print("Format of each line: "); System.out.println("operator number"); System.out.println("For example: + 3"); System.out.println("To end, enter the letter e."); doCalculation( ); } catch(UnknownOpException e2) { System.out.println(e2.getMessage( )); System.out.println("Try again at some other time."); System.out.println("Program ending."); System.exit(0); } catch(DivideByZeroException e3) { handleDivideByZeroException(e3); } } } DivideByZeroException.java public class DivideByZeroException extends Exception { static final long serialVersionUID = -1L; public DivideByZeroException( ) { super("Dividing by Zero!!"); } public DivideByZeroException(String message) { super(message); } } UnkownOpException.java public class UnknownOpException extends Exception { static final long serialVersionUID = -1L; 4 public UnknownOpException( ) { super("UnknownOpException"); } public UnknownOpException(char op) { super(op + " is an unknown operator."); } public UnknownOpException(String message) { super(message); } } (a) Write Calculator.java DivideByZeroException.java and UnknownOpException.java as shown above (from the textbook). Run the program analyze the output. (b) Add the following code after doCalculation() method in Calculator.java public void doCalculation2( ) throws DivideByZeroException, UnknownOpException { Scanner keyboard = new Scanner(System.in); boolean done = false; result = 0; System.out.println("result = " + result); while (!done) { char nextOp = (keyboard.next( )).charAt(0); if ((nextOp == 'e') || (nextOp == 'E')) done = true; else { double nextNumber = keyboard.nextDouble( ); try{ result = evaluate(nextOp, result, nextNumber); System.out.println("result " + nextOp + " " + nextNumber + " = " + result); System.out.println("updated result = " + result); }catch (DivideByZeroException e){ System.out.println(e.getMessage() + " Re-throws from doCalculation2 " + e.toString()); throw e; } catch (UnknownOpException e){ 5 System.out.println(e.getMessage() + " Re-throws from doCalculation2"); throw e; } } } } (c) Change the statement clerk.doCalculation(); in main method to clerk.doCalculation2() Change the statement clerk.doCalculation(); in handleUnknownOpException() method to clerk.doCalculation2(). Run the program and analyze the result. (d) Remove try and catch blocks (clauses) from the main(). You can do this by adding comments to these statements. See whether you can compile your program. Explain why you have syntax error. Explain two different ways of fixing the syntax error. Task 2: Write the following program based on the code template. public class Task2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); try { if (number2 == 0) //throw new ArithmeticException() object with the message "Divisor cannot be zero" System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); } catch (_________________) {// catch an exception //print out message of the exception caught } System.out.println("Execution continues ..."); } } Task 3: Write the following code and execute to understand how to use printStackTrace() method to trace chained exceptions. public class Task3 { 6 public static void main(String[] args) { try { method1(); } catch (Exception ex) { ex.printStackTrace(); } } public static void method1() throws Exception { try { method2(); } catch (Exception ex) { throw new Exception("New info from method1", ex); } } public static void method2() throws Exception { throw new Exception("New info from method2"); } } Task 4: Write the following program to understand finally block import import import import java.io.PrintWriter; java.util.Scanner; java.io.File; java.io.FileNotFoundException; public class Task4 { public static void main(String[] args) { java.io.PrintWriter output = null; Scanner input = null; try { // Create a file output = new PrintWriter("./src/lab8/text.txt"); // Write formatted output to the file output.println("Welcome to Java\n Welcome to Java"); input = new Scanner(new File("./src/lab8/text.txt")); while(input.hasNextLine()){ String line = input.nextLine(); 7 System.out.println(line); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } finally { // Close the file if (output != null) output.close(); } System.out.println("End of the program"); } } (a) Run the program and analyze the result. (b) Write the following code after finally{} block and run the program. Analyze the result. try{ input = new Scanner(new File("./src/lab8/text.txt")); while(input.hasNextLine()){ String line = input.nextLine(); System.out.println(line); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } (c) Add the following finally block after the code you added in question (b), run the program. Analyze the result. finally { // Close the file if (input != null) input.close(); System.out.println("Now closing input stream..."); } Task 5: To understand rules for object serialization Contain.java import java.io.Serializable; class Contain implements Serializable{ private static final long serialVersionUID = 1L; int containValue = 11; public String toString() 8 { return ("value in Contain class= " + containValue); } } Parent.java //import java.io.Serializable; class Parent { static final long serialVersionUID = 1L; int parentValue = 10; Parent(){ parentValue = 10; } Parent(int value){ parentValue = value; } //private int parentValue = 10; public String toString() { return ("parentValue = " + parentValue); } } SerialTest.java import import import import import import java.io.FileInputStream; java.io.ObjectInputStream; java.io.Serializable; java.io.IOException; java.io.FileOutputStream; java.io.ObjectOutputStream; public class SerialTest extends Parent implements Serializable { static final long serialVersionUID = 1L; int value = 66; Contain con = new Contain(); public int getValue() { return value; 9 } public static void main(String args[]) throws IOException { FileOutputStream fos = new FileOutputStream("/AAASource/temp.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); SerialTest st = new SerialTest(); oos.writeObject(st); oos.flush(); oos.close(); ObjectInputStream inputStream = null; try { inputStream = new ObjectInputStream( new FileInputStream("/AAASource/temp.out")); } catch(IOException e) { System.out.println("Error opening input file " + "//AAASource//temp.out"); System.exit(0); } SerialTest readOne = null; try { readOne = (SerialTest)inputStream.readObject( ); inputStream.close( ); } catch(Exception e) { System.out.println("Error reading from file " + "//AAASource//temp.out"); System.exit(0); } System.out.println("The following were read\n" + "from the file " + "//AAASource//temp.out"); System.out.println(readOne.toString()); System.out.println( ); System.out.println("End of program."); }// of main public String toString() 10 { return (super.toString() + " " + con.toString() + " " + "my value " + value); } }//of class (a) Execute SerialTest.java to understand the serialization (b) Comment the default constructor in Parent.java, see if there exist any syntax errors. (c) Uncomment import statement in Parent.java. Redefine the class by the statement class Parent implements Serializable. See you still have syntax errors. (d) Uncomment the default constructor in Parent.java. Then remove implements Serializable from the Contain.java class definition. See whether you have any syntax errors. Run SerialTest.java to see whether the program throws any run-time exceptions. 11