编写Test类,该类有一个divide(int a,int b)方法,用来计算a/b的值.因为参数b有可能是0,因此在做除法时,要捕获异常.一旦捕获到异常,给出提示;“分母不能为0!”.该方法的返回值是int型的.2编写Main

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/20 21:02:52

编写Test类,该类有一个divide(int a,int b)方法,用来计算a/b的值.因为参数b有可能是0,因此在做除法时,要捕获异常.一旦捕获到异常,给出提示;“分母不能为0!”.该方法的返回值是int型的.2编写Main
编写Test类,该类有一个divide(int a,int b)方法,用来计算a/b的值.因为参数b有可能是0,因此在做除法时,要捕获异常.一旦捕获到异常,给出提示;“分母不能为0!”.该方法的返回值是int型的.
2编写Main类,在Main类的main方法中,创建一个Test类的对象,然后让用户输入两个数,以这两个数作为Test对象divide方法的参数计算除法运算的结果.

编写Test类,该类有一个divide(int a,int b)方法,用来计算a/b的值.因为参数b有可能是0,因此在做除法时,要捕获异常.一旦捕获到异常,给出提示;“分母不能为0!”.该方法的返回值是int型的.2编写Main
import java.util.*;
public class Test{
public int divide(int a, int b){
try{
return a/b;
}catch(ArithmeticException e){
System.out.println("分母不能为0!");
System.exit(1);
return 0;
}
}
public static void main(String[] args) {
Test app = new Test();
int n1 = 0;
int n2 = 0;
try{
Scanner in1 = new Scanner(System.in);
System.out.println("输入第一个数:");
n1 = in1.nextInt();
System.out.println("输入第二个数:");
n2 = in1.nextInt();
System.out.println(app.divide(n1,n2));
}catch(InputMismatchException e){
System.out.println("输入格式有误");
}catch(Exception e){
System.out.println("error.");
}
}
}