Division by Zero
Completed
Read pairs of integers and print a / b (integer division), or cannot divide by zero by catching ArithmeticException.
Input
n, then n lines a b.
Output
n lines.
Example
Input
3 10 3 5 0 -9 2
Output
3 cannot divide by zero -4
Editor
Java
Hints
Integer division by zero throws ArithmeticException (double division gives Infinity instead).
Solution explanation
Note the difference: 5 / 0 throws, but 5.0 / 0 is Infinity.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int a = sc.nextInt(), b = sc.nextInt();
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("cannot divide by zero");
}
}
}
}