捕获整数除法异常 分数 25 作者 刘凤良 单位 天津仁爱学院 请仔细阅读下面的代码,根据方法内的提示,在 Begin - End 区域内进行代码补充,具体任务如下: 编辑器中的代码运行时可能会有异常,请利用相关知识处理该异常。 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num1 = sc.nextInt(); int num2 = sc.nextInt(); /********* Begin *********/ System.out.println(num1/num2); /********* End *********/ } } 输入格式: 输入两个整数a b。 输出格式: 输出 a/b 的值。 输入样例1: 4 2 输出样例1: 2 输入样例2: 4 0 输出样例2: 除数不能为0
时间: 2023-07-06 21:29:28 浏览: 873
以下是代码实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
try {
System.out.println(num1/num2);
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
}
}
}
```
代码思路:
1.在执行整数除法时,可能会出现除数为0的情况,会抛出ArithmeticException异常。
2.在main函数中,使用try-catch语句捕获该异常,如果出现除数为0的情况,则输出“除数不能为0”;否则输出a/b的值。
3.注意,在除法运算前,需要先读入两个整数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)