package a0418;
import a0418.Exception.AgeException;
import a0418.Exception.MathStringException;
import a0418.Exception.NameException;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Girlfriend a=new Girlfriend();
Scanner sc=new Scanner(System.in);
while (true) {
try {
System.out.println("请输入你的女朋友的姓名:");
String name=sc.next();
a.setName(name);
System.out.println("请输入女朋友的年龄:");
String age=sc.next();
int ag=Integer.parseInt(age);//字符串转数字!!!!!!!
a.setAge(ag);
System.out.println(".......成功。。。。。。。");
break;
} catch (NumberFormatException e) {
System.out.println("输入数字地方输入了字符串");
}catch (NameException | AgeException e) {
System.out.println(e.getMessage());
}
}
}
}
package a0418;
import a0418.Exception.AgeException;
import a0418.Exception.NameException;
public class Girlfriend {
private String name;
private int age;
public Girlfriend() {
}
public Girlfriend(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
if(name.length()>3){
throw new NameException(name+"名字有误名字长度应该不大于3");
}
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>40||age<18){
throw new AgeException(age+"年龄有误,应该为18-40之间");
}
this.age = age;
}
}
package a0418.Exception;
/*运行时异常:由于参数问题而导致的错误;
* 编译时异常:提醒程序员检查本地信息:
* eg: 数据库连接异常
本地文件异常
。。。。。。
* */
public class AgeException extends RuntimeException{
public AgeException() {
}
public AgeException(String message) {
super(message);
}
}
package a0418.Exception;
public class NameException extends RuntimeException{
public NameException() {
}
public NameException(String message) {
super(message);
}
}