实验3异常处理和常用实用类Word文件下载.docx
《实验3异常处理和常用实用类Word文件下载.docx》由会员分享,可在线阅读,更多相关《实验3异常处理和常用实用类Word文件下载.docx(10页珍藏版)》请在冰豆网上搜索。
handleexceptionSystem.out.println(异常是:
+e.getMessage();
System.out.println(异常是:
+e.toString();
e.printStackTrace();
答:
getMessage的作用是返回此throwble的详细消息字符串;
toString的作用是返回此throwble的简短描述。
结果是此对象类的名字,冒号和一个空格和调用此对象getLocalizedMessage()方法的结果。
如果getLocalizedMessage返回null,则只返回类名称。
printStackTrace将此throwable及其追踪输出至标准错误流。
此方法将此Throwable对象的堆栈跟踪输出至错误输出流,作为字段System.err的值。
输出的第一行包含此对象的toString()方法的结果。
剩余行表示以前由方法fillInStackTrace()记录的数据。
实验题2用户自定义异常:
编写一个程序,用来检查输入的字符串是否含有非英文字符(即A-Z和a-z以外的字符)。
1.定义一个异常类IllegalCharacterException,让其继承异常类Exception;
2.写一个CheckString类,为其添加静态方法check(Stringstr),当str中含有非英文字符时,不做异常处理,只将产生的异常抛出,抛出的异常参数message为:
“字符串含有非英文字符!
”;
3.在主类ExceptionTest中进行测试,输入多个字符串,使用try-catch对捕获的异常进行处理。
实验题3常用实用类Calendar练习。
编写一个能够显示日历的程序,程序效果截图如下:
基本要求1.默认显示系统当前月份,接受标准输入,当键盘输入“p”并回车时,显示上一月日历,当键盘输入“n”并回车时,显示下一月日历;
2.使用Calendar类开发该程序,在API中熟悉Calendar类的常量、get方法、set方法,roll()等基础内容之后再开发程序。
packageCalendar;
importjava.util.*;
publicclassCalendarBeanintyear=0;
intmonth=0;
voidsetYear(intyear)this.year=year;
voidsetMonth(intmonth)this.month=month;
publicvoidgetCalender()Stringa=newString35;
Calendarrili=Calendar.getInstance();
rili.set(year,month-1,1);
intweekDay=rili.get(Calendar.DAY_OF_WEEK)-1;
/返回当前日期所对应的星期,1表示是星期日,以此类推intday=0;
if(month=1|month=3|month=5|month=7|month=8|month=10|month=12)day=31;
if(month=4|month=6|month=9|month=11)day=30;
if(month=2)if(year%4=0)&
(year%100!
=100)|(year%400=0)day=28;
elseday=29;
for(inti=0;
iweekDay;
i+)ai=;
for(inti=weekDay,n=1;
iday+weekDay;
i+)ai=String.valueOf(n);
/将int转化为Stringn+;
for(inti=weekDay+day;
ia.length;
System.out.println(year+年+month+月);
charstr=日一二三四五六.toCharArray();
for(charc:
str)/输出日历的最上方一行System.out.printf(%3s,c);
ia.length;
i+)if(i%7=0)System.out.println();
System.out.printf(%4s,ai);
publicclassCalendarTestpublicstaticvoidmain(Stringargs)/TODO自动生成的方法存根CalendarBeancal=newCalendarBean();
CalendarnowDate=Calendar.getInstance();
nowDate.setTime(newDate();
intyear=nowDate.get(Calendar.YEAR);
intmonth=nowDate.get(Calendar.MONTH)+1;
cal.setYear(year);
cal.setMonth(month);
cal.getCalender();
System.out.println(nprevious(p)ornext(n)month:
);
charch;
Scannerscanner=newScanner(System.in);
ch=scanner.next().charAt(0);
/从键盘接受一个字符while(ch=n|ch=p)if(ch=n)if(month1)month=month-1;
elseyear=year-1;
month=12;
/System.out.println(n);
Scannerscanner2=newScanner(System.in);
ch=scanner2.nextLine().charAt(0);
实验题4正则表达式的使用。
某网站注册了若干用户(User类),注册过程中,必须要检查用户的以下输入信息:
用户名(userName)、密码(userCode)、邮箱(email)、电话(phoneNumber)。
用户输入时,这4个信息都被保存成String类型。
这4个字段的规则如下:
用户名:
用户名是由字母、数字或“_”组成,长度不少于6位,不多于30位;
密码:
包含字母、数字、标点符号在内的816位字符;
邮箱:
(a-z0-9A-Z+-|.?
)+a-z0-9A-Z(a-z0-9A-Z+(-a-z0-9A-Z+)?
.)+a-zA-Z2,3$电话:
11位数字字符串。
基本要求写一个类UserFilter用于判断一个User对象的4个成员变量是否满足要求。