题目:
【问题描述】
输入两个数,输出两个数的商,自定义异常类NegativeException和ZeroException用于检测输入的除数为负数和零时,抛出异常。
【输入形式】
请输入第一个数:
请输入第二个数:
【输出形式】
商是:
【输入输出样例1】
Please input first number:
5
Please input second number:
2
Divisor is : 2.5
finally!
【输入输出样例2】
Please input first number:
5
Please input second number:
-2
The divisor, -2, could not be negative!
finally!
【输入输出样例3】
Please input first number:
5
Please input second number:
0
The divisor, 0,could not be zero!
finally!
代码:
import java.util.Scanner;
class NegativeException extends Exception{
String message;
public NegativeException(int n){
message = "The divisor, "+n+", could not be negative!";
}
}
class ZeroException extends Exception{
String message;
public ZeroException(int m){
message = "The divisor, "+m+",could not be zero!";
}
}
class My{
public My(int m,int n)throws Exception{
if(n<0) {
throw new NegativeException(n);
}
else if(n==0) {
throw new ZeroException(n);
}
else {
System.out.println("Divisor is : "+(float)m/n);
}
}
}
public class zhong{
public static void main(String[] args) throws Exception {
Scanner in=new Scanner(System.in);
System.out.println("Please input first number: ");
int m=in.nextInt();
System.out.println("Please input second number: ");
int n=in.nextInt();
try {
new My(m,n);
}
catch(NegativeException e ) {
System.out.println(e.message);
}
catch(ZeroException e ) {
System.out.println(e.message);
}
System.out.println("finally!");
}
}