练习要求:键盘录入女朋友的姓名和年龄,年龄范围在18~40之间,姓名长度在0~100之间,如果不符合条件就会重新录入到录入成功为止。
1.代码部分
public class GrilFrend {
String name;
int age;
public void setName(String name) {
if(name.length()>0&&name.length()<100&&name!=null){
this.name=name;
}else{
throw new helloException();
}
}
public void setAge(int age) {
if(age>18&&age<40){
this.age=age;
}else{
throw new helloException();
}
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
import java.util.Scanner;
public class 异常 {
public static void main(String args[]){
GrilFrend a=new GrilFrend();
Scanner sc=new Scanner(System.in);
while(true){
try{
System.out.print("请输入女朋友姓名:");
a.setName(sc.nextLine());
System.out.print("\n请输入女朋友年龄:");
a.setAge(sc.nextInt());
System.out.println("\n"+"女朋友年龄:"+a.age+" 女朋友姓名:"+a.name);
break;
}catch(helloException e){
System.out.println("输入年龄或者姓名有错误");
}
}
}
}
public class helloException extends RuntimeException{
public helloException() {
}
public helloException(String message) {
super(message);
}
}
收获:
1.自定义异常的创建步骤。
2.如果自定义异常需要应用到try中需要自己手动trow抛出异常,才能够被捕获。
3.复习了scanner类
观看谨慎,总结可能存在错误,代码也不是很完善。