JAVA 异常捕捉机制(1)---除数为0

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingzhuo_126/article/details/83152753

要求

  • 完成一个 java application应用程序,完成c=a/b 的计算并输出c的结果,可以为a和b在程序中赋初值、或者接收用户通过键盘输入a和b的数值文本后转换为数字等,在程序要求当 b 为0时c的计算结果正确。

程序一

一. 在程序中给a,b赋初值

class ExcDemo_1 {
	public static void main(String args[]) { //主方法
		int a[] = {4, 8, 16, 32, 64 ,128}; //为数组a赋值,作为被除数
		int b[] = {2, 0, 4, 4, 0, 8};      //为数组b复制,作为除数
		
		for(int i=0; i<a.length; i++) {
			try {  //要监视的代码
				System.out.println(a[i] + " / " + b[i] + " is " + a[i]/b[i]);
			}
			catch (ArithmeticException exc) {  //捕获除数为0这个异常
				System.out.println("Can't divide  by zero");
			}
		}
	}
}

运行结果:

在这里插入图片描述

程序二

二. 通过键盘输入a,b

import java.util.Scanner;//导入java.util包下的Scanner类
class ExcDemo_2 {
	public static void main(String args[]) {  //主方法入口
		while(true) {
			Scanner scan = new Scanner(System.in);//创建Scanner对象,等待键盘输入
			System.out.println("a= ");
			int a = scan.nextInt(); //定义a的值
			System.out.println("b= ");
			int b = scan.nextInt();//定义b的值
			
			try {  //要监视的代码
				int c = (a/b);
				System.out.println("c =  " + c);
			}
			catch (ArithmeticException exc) {//捕获除数为0这个异常
				System.out.println("Can't divide  by zero");
			}
			
		}
	}
}

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mingzhuo_126/article/details/83152753