Docsity

Java Exception Handling Exercise: Division Operation - Prof. Guerra, Assignments of Java Programming

Toggle sidebar
bg1
// import the package to accept the input
import java.io.*;
public class ExceptionExercise1
{
public static void main(String[] args) throws Exception
{
// create object for the input
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
// create and declare the local variables
String first;
String second;
int dividend;
int divisor;
int answer;
try
{
//Ask the user for the first number
System.out.print("Enter the first number: ");
first = dataIn.readLine();
//Ask the user for the second number
System.out.print("Enter the second number: ");
second = dataIn.readLine();
//convert the input to numbers
dividend = Integer.parseInt(first);
divisor = Integer.parseInt(second);
//perform division
answer = (dividend/divisor);
//display the result
System.out.println("The answer is " + answer + ".");
}
catch(ArithmeticException ex)
{
System.out.println("Error! " + ex.getMessage() + ".");
System.out.println("Try Again.");
}
catch(NumberFormatException ex)
{
System.out.println("Error! " + ex.getMessage() + ".");
System.out.println("Try Again.");
}
finally
{
System.out.println("Programming is fun.");
System.out.println("I am starting to love it.");
}
}
}
pf2

Partial preview of the text

Download Java Exception Handling Exercise: Division Operation - Prof. Guerra and more Assignments Java Programming in PDF only on Docsity!

// import the package to accept the input import java.io.*; public class ExceptionExercise { public static void main(String[] args) throws Exception { // create object for the input BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); // create and declare the local variables String first; String second; int dividend; int divisor; int answer; try { //Ask the user for the first number System.out.print("Enter the first number: "); first = dataIn.readLine(); //Ask the user for the second number System.out.print("Enter the second number: "); second = dataIn.readLine(); //convert the input to numbers dividend = Integer.parseInt(first); divisor = Integer.parseInt(second); //perform division answer = (dividend/divisor); //display the result System.out.println("The answer is " + answer + "."); } catch(ArithmeticException ex) { System.out.println("Error! " + ex.getMessage() + "."); System.out.println("Try Again."); } catch(NumberFormatException ex) { System.out.println("Error! " + ex.getMessage() + "."); System.out.println("Try Again."); } finally { System.out.println("Programming is fun."); System.out.println("I am starting to love it."); } } }