Create a java program which allows the user to enter two values (Using JOptionPane) to be divided. The program catches an exception if either of the entered values is not an integer.
Declare three integers—two to be input by the user and a third to hold the result after dividing the first two. The numerator and denominator variables must be assigned starting values because their values will be entered within a try block. Also declare an input String to hold the return value of the JOptionPane showInputDialog() method.int numerator = 0, denominator = 0, result; String display;
Add a try block that prompts the user for two values, converts each entered String to an integer, and divides the values, producing result(Cast the result to a double).
Add a catch block that catches an Arithmetic Exception object if division by 0 is attempted. If this block executes, display an error message, and force result to 0.
import javax.swing.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = 0, y = 0;
double z = 0;
try {
String inp1 = JOptionPane.showInputDialog("numerator: ");
x = Integer.parseInt(inp1);
String inp2 = JOptionPane.showInputDialog("denominator : ");
y = Integer.parseInt(inp2);
z = x / y;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.print(z);
}
}
}
Comments
Leave a comment