In: Computer Science
Consider the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = "";
System.out.println("Enter the first number: ");
input = in.nextLine();
int a = 0;
int b = 0;
a = Integer.parseInt(input);
System.out.println("Enter the second number: ");
input = in.nextLine();
b = Integer.parseInt(input);
int result = 0;
result = a/b;
System.out.println("a/b : " + result);
}
Copy the code to your Main.java file and run it with the following
inputs:
34 and 0;
‘Thirty-four’ as the first input.
What prevented the program from running successfully?
Update the code, so that it can handle cases a) and b).
Please note the following:
You have to use try-catch to handle
exceptions.
To determine exception classes, that you need to catch, use error
message from the respective case (a) and b)). Hint: to
handle String-to-integer conversion, use
NumberFormatException;
Exceptions should be caught so that:
Code never crashes due to non-numeric input (both for first and
second values);
Code never crashes due to division by zero;
If non-numeric value is entered for a or b, program should output
"Error: entered value is not an integer number. Exiting..." and
exit (use System.exit(0); to exit);
If zero value is entered for b, program should output " Error:
cannot divide by zero. Exiting..." and exit (use System.exit(0); to
exit);
Hints: Use 3 try-catch blocks in total. Try block
should only contain the command, that can throw an
exception.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = "";
System.out.println("Enter the first number: ");
input = in.nextLine();
int a = 0;
int b = 0;
// First try catch block
try {
a = Integer.parseInt(input);
}catch(NumberFormatException ex) {
System.out.println("Error: entered value is not an integer number. Exiting...");
System.exit(0);
}
System.out.println("Enter the second number: ");
input = in.nextLine();
// Second try catch block
try {
b = Integer.parseInt(input);
}catch(NumberFormatException ex) {
System.out.println("Error: entered value is not an integer number. Exiting...");
System.exit(0);
}
int result = 0;
//Third try catch block
try {
result = a / b;
} catch(Exception e) {
System.out.print(" Error: cannot divide by zero. Exiting...");
System.exit(0);
}
System.out.println("a/b : " + result);
}
}
OUTPUT: