Challenge: Safe Division
Completed
Read two lines of text. Try to turn both into whole numbers and print the first divided by the second (integer division). If either line isn't a whole number, print Invalid number. If the second is 0, print Cannot divide by zero. Use try/catch.
Input
Two lines of text.
Output
The result, or one of the two messages.
Example
Input
20 4
Output
5
Editor
Java
Hints
Integer.parseInt throws NumberFormatException for bad text.
a / b throws ArithmeticException when b is 0.
Solution explanation
Two catch blocks give a different message for each kind of problem.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String x = sc.nextLine().trim();
String y = sc.nextLine().trim();
try {
int a = Integer.parseInt(x);
int b = Integer.parseInt(y);
System.out.println(a / b);
} catch (NumberFormatException e) {
System.out.println("Invalid number");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module