CS 1401, Quiz 11

Date: Monday, November 20, 2006
Name (please type legibly, ideally in block letters): ______________________________________________________________________

1. Write a main method that asks the user for two integers, and then computes and prints the integer result of dividing the first input by the second one. Use try/catch block to produce a meaningful error message when the second input is 0 (i.e., when we cannot divide).

Solution:

public static main(String[] args){
  Console reader = new Console(System.in);
  System.our.println("Please enter the first input.");
  int input1 = reader.nextInt();
  System.our.println("Please enter the second input.");
  int input2 = reader.nextInt();
  try{
    int result = input1 / input2;
    System.out.println("The result of dividing " + input1 + "  by " +
      input2 + " is " + result + ".");
  }
  catch(ArithmeticException a){
    System.out.println("Your second input was 0, but Java does not allow dividing by 0.");
  }
}