练习11
- 自定义异常类,模拟电梯载重的安全提示“超载”。
(1) 继承Exception异常类,实现自定义电梯载重超载异常提示;
(2) 定义应用类,通过接口方法接收电梯实际载重量,通过阈值设定,做出相应报警提示。实际承重通过控制台输入。 - 模拟用户注册中的信息检测。
(1)继承Exception自定义用户提交注册信息的异常类,对电话号码输入进行异常提示;
(2)定义应用类,通过接口方法接收电话号码,检测其长度是否为11位,不符则抛出异常并提示。输入电话号码通过控制台输入。
package practice11;
import java.util.Scanner;
class ElevatorException extends Exception{
private static final long serialVersionUID = 1L;
private String message;
private int load;
public ElevatorException(String message,int load){
super(message);
this.message=message;
this.load=load;
}
public String getMessage(){
return this.message;
}
public int getLoad(){
return this.load;
}
}
public class Test1 {
private static int load_limited=1000;
public static void f(int load) throws ElevatorException{
if(load>load_limited) {
throw new ElevatorException("the load is over",load);
}
else System.out.println("the load is normal");
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入的电梯现在的载重:");
int load=sc.nextInt();
sc.close();
try {
f(load);
} catch (ElevatorException e) {
System.out.println("载重情况:"+e.getMessage()+"\n"+"电梯的现在的载重为"+e.getLoad());
}
}
}
package practice11;
import java.util.Scanner;
class InfoException extends Exception{
private static final long serialVersionUID = 1L;
String number;
String message;
public InfoException(String message,String number){
super(message);
this.message=message;
this.number=number;
}
public String getNumber(){
return this.number;
}
}
public class Test2 {
public void judge(String str) throws InfoException{
char s[]=str.toCharArray();
if(s.length!=11){
throw new InfoException("the number is error",str);
}
else System.out.println("the number is normal");
}
public void manage(String str){
try {
judge(str);
} catch (InfoException e) {
System.out.println("输入的电话号码错误:"+e.getNumber());
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String string=sc.nextLine();
sc.close();
Test2 t=new Test2();
t.manage(string);
}
}