要求
(1)自定义两个异常类非法姓名异常IllegaNameException和非法地址异常IllegalAddressException。
(2)定义Student类包含Name和Address属性,和setName、setAddress方法,当姓名长度小于1或者大于5抛出IllegaNameExceptio,当地址中不含有”省”或者“市”关键字抛出IllegalAddressException。
(3)在main方法中进行捕获试验。
代码
package exam6;
import java.util.Scanner;
class illegalNameException extends Exception
{
public illegalNameException()
{
super("姓名不合法,长度小于1或大于5\n请重新输入姓名");
}
// public illegalNameException(String msg)
// {
// super(msg);
// }
}
class illegalAddressException extends Exception
{
public illegalAddressException()
{
super("给定地址不合法,未包含省/市\n请重新输入地址");
}
// public illegalAddressException( String msg)
// {
// super(msg);
// }
}
public class Student
{
String name,address;
public void setName(String name)
{
try
{
if(name.length()>5||name.length()<1)
throw new illegalNameException();
else
{
this.name=name;
}
}
catch(illegalNameException e)
{
System.out.println(e.getMessage());
Scanner a=new Scanner(System.in);
String str1=a.nextLine();
setName(str1);
}
}
public void setAddress(String address)
{
int n=address.length();
char[] temp=address.toCharArray();
boolean flag=false;
for(int i=0;i<n;i++)
{
if(temp[i]=='省'|| temp[i]=='市')
{
flag=true;
break;
}
}
try
{
if(flag)
{
this.address=address;
}
else
throw new illegalAddressException();
}
catch(illegalAddressException e)
{
System.out.println(e.getMessage());
Scanner a=new Scanner(System.in);
String str1=a.nextLine();
setAddress(str1);
}
}
public void showMessage()
{
System.out.println("--------------------------------------------------------------------------------------------");
System.out.println("姓名:"+name);
System.out.println("地址:"+address);
}
public static void main(String args[])
{
System.out.println("请输入学生的姓名(长度1~5):");
Student s1=new Student();
Scanner se = new Scanner (System.in);
s1.name=se.nextLine();
s1.setName(s1.name);
System.out.println("请输入地址(包含省/市):");
s1.address=se.nextLine();
s1.setAddress(s1.address);
s1.showMessage();
}
}