IN Java GUI Objective: Utilize try-catch statements in a Java program to catch a
ID: 3917300 • Letter: I
Question
IN Java GUI
Objective: Utilize try-catch statements in a Java program to catch an ArithmeticException and an InputMismatchException.
The Problem
The program must use OOP style and have more than one class containing methods.
The program must at some point ask the user for the input of numbers.
There must be methods to handle the input of the numbers to insure that type mismatches should not crash the program.
The program must do at least one calculation. If it is possible to have a division by zero, there should be a try-catch to catch it and prevent the program from crashing.
There must be at least one try-catch statement in your program.
1. Before You Begin
2. The Assignment
2.1. Specifications
2.2. General
Use good comments in the body of the program.
Think about the problem and decide what type each of the input numbers should be. Also, think about the calculations and decide what type the variables should be that will hold the results of the calculations.
Use camel casing for variable names, and use descriptive variable names. Do not use general variable names like "tax" or "total."
Take a look at the method below.
This method will cause the program to crash.
Example 1: A method that tries to perform an impossible task
Here is another example of a method that asks for an int and displays the number entered.
A good way to handle a situation like this is to have a method (think one task) that will return an int from the user, but will continue to ask for input until an int is received. This would prevent a type mismatch and cause the program to end.
You could use this method any time you needed an int from the user. You might also create a method for doubles as well.
You would not put the prompting in the method because the prompting would be different in each program.
Example 2: A method that will return an int.
You will have a good bit of leeway in completing this problem.You may create any problem you like, as long as it meets the specifics below. It can be written to display the results in the terminal, or it can be written in GUI style.
Explanation / Answer
import java.util.*;//package for reading values from user.
class display //This class will check the the arithmetic exception.
{
public display(int x,int y) //Constructor of display class
{
//try block
try {
int result = x / y;
System.out.println("Division = " + result);
}
// catch block
catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero."); //Divide by Zero Exception.
}
}
}
public class Main
{
public static void main(String[] args) {
System.out.println("Enter two integer values: ");
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
display dis = new display(a,b);
}
}