《实验6-异常与字符串(共24页).doc》由会员分享,可在线阅读,更多相关《实验6-异常与字符串(共24页).doc(24页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。
1、精选优质文档-倾情为你奉上南昌大学实验报告学生姓名: 王维 学 号: 专业班级: 网工121班 实验类型: 验证 综合 设计 创新 实验日期: 实验成绩: 实验6 异常与字符串(String类)的使用一、实验目的1、掌握异常处理机制的运作2.掌握处理异常的几个子句:trycatch.finally、thorws和throw3、掌握String类和StringBuffer类的基本使用方法4、通过上机编写和运行关于字符串的程序来加深对String类和StringBuffer类等的了解二、实验内容(1)课本P367 13.19 和P368 13.113.19异常类:public class Inva
2、lidRadiusException extends Exception private static final long serialVersionUID = 1L;private double radius;public InvalidRadiusException(double radius) super(Invalid radius + radius);this.radius = radius;public double getRadius() return radius;Circle类:public class Circle private double radius;privat
3、e static int numberOfObjects = 0;public Circle() throws InvalidRadiusException this(1.0);public Circle(double newRadius) throws InvalidRadiusException setRadius(newRadius);numberOfObjects+;public double getRadius() return radius;public void setRadius(double newRadius) throws InvalidRadiusException i
4、f (newRadius = 0)radius = newRadius;elsethrow new InvalidRadiusException(newRadius);public static int getNumberOfObjects() return numberOfObjects;public double findArea() return radius * radius * 3.14159;13.1使用异常public class Exercise13_1 public static void main(String args) if (args.length != 3) Sys
5、tem.out.println(Please use Exercise13_1 operand1 operator operand2);return;String op1 = args1;String op = args2;String op2 = args3;double a, b;try a = Double.parseDouble(op1); catch (Exception e) System.out.println(Wrong Input: + op1);return;try b = Double.parseDouble(op2); catch (Exception e) Syste
6、m.out.println(Wrong Input: + op2);return;switch (op.charAt(0) case +:System.out.println(a + b);break;case -:System.out.println(a - b);break;case *:System.out.println(a * b);break;case /:System.out.println(a / b);break;13.1不使用异常public class Exercise13_01 public static void main(String args) if (args.
7、length != 3) System.out.println(Please use Exercise13_1 operand1 operator operand2);return;String op1 = args0;String op = args1;String op2 = args2;double a, b;if (isNum(op1) = false) System.out.println(Wrong Input: + op1);return;if (isNum(op2) = false) System.out.println(Wrong Input: + op2);return;a
8、 = Double.parseDouble(op1);b = Double.parseDouble(op2);System.out.print(a + + op + + b + = );switch (op.charAt(0) case +:System.out.println(a + b);break;case -:System.out.println(a - b);break;case *:System.out.println(a * b);break;case /:System.out.println(a / b);break;static boolean isNum(String a)
9、 for (int i = 0; i a.length(); i+) char c = a.charAt(i);if (0 = c & c = 9)continue;else if (c = . & (i != 0 | i != a.length() - 1)continue;elsereturn false;return true;(2)课本P272 9.19import java.io.File;import java.io.IOException;import java.io.PrintWriter;class WriteFile private String name;public W
10、riteFile(String name) this.name = name;public void writeFile() File fi = new File(name);try PrintWriter pw = new PrintWriter(fi);for (int i = 0; i 100; i+) int t = (int) (Math.random() * 10000);pw.print(t + n);pw.close(); catch (IOException e) e.printStackTrace();public class Exercise9_19 public sta
11、tic void main(String args) WriteFile wf = new WriteFile(src/shiyan6/Exercise9_19.txt);wf.writeFile();(3)编写一个与居民身份证有关的程序,可以是Applet或者Application。要求创建一个类,该类至少具有以下3个方法:1)检验居民身份证的真伪,若为假身份证,需要提供其虚假信息,比如居民出生年月日有错等。2)获取真实居民身份证的信息,该信息包括4个部分: 该身份证是新身份证还是旧身份证。 该居民身份证的地址码,如果同学有最新县及县以上行政区划代码可得到居民身份证详细的省、市、县(区)的名
12、称,若没有则只需显示地址码信息即可。 该居民的出生年月日。 该居民的性别。3)将15位的旧身份证转换成18位的新身份证。【参考资料】1)旧身份证共有15位,其格式如下:假设身份证号码为:1001地 址 码出生日期码顺 序 码440524800101001广东省汕头市潮阳县出生年出生月出生日2)新身份证共有18位,其格式如下:假设身份证号码为:地 址 码出生日期码顺序码校验码440524198001010013广东省汕头市潮阳县出生年出生月出生日3)地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按 GB/T 2260的规定执行,有条件的同学可以到“中华人民共和国国家统计局”网站(
13、)查看最新县及县以上行政区划代码(截止2003年6月30日),该文章的网址为“4)生日期码表示编码对象出生的年、月、日,按 GB/T 7408 的规定执行。年、月、日代码之间不用分隔符。旧身份证号码的出生日期码只有6位,而新身份证的出生日期码有8位,年份采用4位表示。5)顺序码表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配给女性,该顺序码有3位。6)校验码采用ISO 7064:1983,MOD 11-2 校验码系统,该校验码只有1位,在新身份证中被采用,其公式为(aiWi)(mod 11),在公式中: i表示号码字符从右至左包括校验
14、码在内的位置序号; ai表示第i位置上的号码字符值; Wi表示第i位置上的加权因子,其数值依据公式Wi=2(i-1)(mod 11)计算得出。 在求出(aiWi)(mod 11)值后依据下表得到校验码:(aiWi)(mod 11)值 0 1 2 3 4 54617181910校验码字符值 1 0 X 9 8 7 6 5 4 3 2三、实验要求1、要求学生在上机实验前一定要非常清楚并灵活运用该章所讲过的内容;2、在上机实验前编写好实验内容要求的程序,以便上机实验时调试、修改等。3、上机实验后,每位学生必须对该次实验内容写一份实验报告,包括程序内容、调试过程、运行情况和结果等。四、实验环境1、PC
15、微机;2、Windows 7操作系统;3、Eclipse程序集成环境。五、实验步骤1、根据题目要求,画出程序流程图;2、给出本程序的java数据结构;3、编写出程序;4、调试程序:给出一些测试数据,检查输出结果。六、流程图与数据结构流程图在最后。三个类: QuYu负责初始化的时候,加载id.txt的内容,并实现根据区域码返回对应区域名称的功能。 IDCard负责绘制界面 Check负责所有功能逻辑,检测身份证号码真伪。o isTrue方法,总方法,调用其它检测方法,用于检测是否为真身份证号o trueQuYu方法,检测区域码,是否为真,并得出身份证地址。o trueBirth方法,检测出生日期
16、是否合法,并获得出生年月日。o checkCode方法,计算出身份证号的校验码位o checkSex方法,通过顺序码。求出性别o toNewCode方法,将旧身份证转换为新身份证号。注:id.txt为区域码及其对应区域的文本文件。部分内容如下:七、代码QuYu类:package shiyan6.idcard;import java.io.BufferedReader;import java.io.FileReader;import java.util.HashMap;import java.util.Map;public class QuYu private Map hm;/地址码privat
17、e String addressCode;private String filename=src/shiyan6/idcard/id.txt;public QuYu(String name) this.addressCode = name;hm = new HashMap();readTxt();SuppressWarnings(resource)public boolean readTxt() boolean flag = false;BufferedReader br = null;try FileReader read = new FileReader(filename);br = ne
18、w BufferedReader(read);String line;String tmp = new String2;while (line = br.readLine() != null) tmp = line.split( );hm.put(tmp0, tmp1); catch (Exception e) e.printStackTrace();return flag;public String getAddress()return (String)hm.get(addressCode);Check类:package shiyan6.idcard;public class Check p
19、rivate String code;private String address;private String error;/ 每月天数。二月在下面特殊计算private static int days = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 ;/ 网上找的身份证前17位的权值private static int weight = 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,8, 4, 2, 1 ;/ 每一位数字所对应的校验码private static char chkcode = 1, 0,
20、 X, 9, 8, 7, 6, 5,4, 3, 2 ;private int year;private int mon;private int day;/ 身份证的类型,旧身份证为true,新身份证为falseprivate boolean type;/ 男为true,女为falseprivate boolean sex;public Check(String code) this.code = code;public String getError() return error;public void setCode(String code) this.code = code;public
21、int getDay() return day;public String getAddress() return address;public int getYear() return year;public int getMon() return mon;public boolean isType() return type;public boolean isSex() return sex;public void setSex(boolean sex) this.sex = sex;public boolean isTrue() if (code.length() = 15)type =
22、 true;else if (code.length() = 18)type = false;else error = 身份证号长度错误;return false;if (!trueQuYu() error = 区域码错误;return false;if (!trueBirth() error = 出生日期错误;return false;if (!type & checkCode(code) != code.charAt(17) error = 校验码有误;return false;if (!checkSex() error = 顺序码有误;return false;return true;/
23、* * 判断区域码真假,并得出出生地址 */private boolean trueQuYu() / sub截取身份证号的地址部分String sub = code.substring(0, 6);QuYu qy = new QuYu(sub);address = qy.getAddress();if (address = null)return false;return true;/* * 判断生日的真假 */private boolean trueBirth() String birthday = type ? code.substring(6, 12) : code.substring(
24、6, 14);int date;if (type = true)birthday = 19 + birthday;try date = Integer.parseInt(birthday); catch (NumberFormatException e) return false;year = date / 10000;mon = (date % 10000) / 100;day = date % 100;if (mon 12 | mon = 0 | day = 0)return false;int run = 0;/ 是不是闰年,用整型来表示,方便下面作加法if (year % 4 = 0
25、& year % 400 != 0)run = 1;if (mon = 2) if (day days2 + run)return false; else if (day daysmon - 1)/ 如果不在该月天数的范围内,则为假生日return false;return true;/* * 求校验码 */private char checkCode(String code) int sum = 0;for (int i = 0; i 17; i+) int a = code.charAt(i) - 0;int w = weighti;sum += a * w;sum %= 11;retur
26、n chkcodesum;/* * 计算性别 */private boolean checkSex() String tmp;if (type)tmp = code.substring(12);elsetmp = code.substring(14, 17);try int seq = Integer.parseInt(tmp);/ 判断奇偶if (seq & 1) = 1)sex = true;elsesex = false; catch (NumberFormatException e) return false;return true;public String toNewCode()
27、/ 使用StringBuffer实现字符串相加,更高效StringBuffer tmp = new StringBuffer(code.substring(0, 6);tmp.append(19);tmp.append(code.substring(6);tmp.append(checkCode(tmp.toString();return tmp.toString();IDCard类:(负责界面显示)package shiyan6.idcard;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.eve
28、nt.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JSeparator;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.Unsu
29、pportedLookAndFeelException;import javax.swing.plaf.nimbus.NimbusLookAndFeel;SuppressWarnings(serial)public class IDCard extends JFrame private JPanel p,p2;private JTextField num, tBirth, tSex, tType, tAddress,tNew;private JLabel lnew;public IDCard() p = new JPanel();p.add(new JLabel(请输入身份证号:);num =
30、 new JTextField(18);p.add(num);JButton ok = new JButton(确定);ok.addActionListener(new OKListener();p.add(ok);add(p, BorderLayout.NORTH);p2 = new JPanel();p2.setLayout(new GridLayout(5, 2, 5, 5);p2.add(new JLabel(身份证类型,JLabel.CENTER);tType = new JTextField(2);/设置文本区不能聚焦,使之无法编辑tType.setFocusable(false)
31、;p2.add(tType);p2.add(new JLabel(性别,JLabel.CENTER);tSex = new JTextField();tSex.setFocusable(false);p2.add(tSex);p2.add(new JLabel(出生日期,JLabel.CENTER);tBirth = new JTextField();tBirth.setFocusable(false);p2.add(tBirth);p2.add(new JLabel(地址,JLabel.CENTER);tAddress = new JTextField();tAddress.setFocus
32、able(false);p2.add(tAddress);lnew = new JLabel(新身份证号,JLabel.CENTER);lnew.setVisible(false);p2.add(lnew);tNew = new JTextField();tNew.setFocusable(false);tNew.setVisible(false);p2.add(tNew);add(new JSeparator(), BorderLayout.CENTER);add(p2, BorderLayout.SOUTH);public static void main(String args)thro
33、ws UnsupportedLookAndFeelException UIManager.setLookAndFeel(new NimbusLookAndFeel();IDCard idcard = new IDCard();idcard.setResizable(false);idcard.setSize(400, 250);idcard.setLocationRelativeTo(null);idcard.setDefaultCloseOperation(EXIT_ON_CLOSE);idcard.setVisible(true);class OKListener implements A
34、ctionListener public void actionPerformed(ActionEvent e) String code;code = num.getText();/去掉身份证号码前后的多余空格code=code.trim();num.setText(code);Check c = new Check(code);/如果是假身份证,弹出错误消息对话框if (!c.isTrue() clear();JOptionPane.showMessageDialog(null, c.getError(),假身份证, JOptionPane.ERROR_MESSAGE);return;tTy
35、pe.setText(c.isType() ? 旧 : 新);tSex.setText(c.isSex() ? 男 : 女);tBirth.setText(c.getYear() + 年 + c.getMon() + 月 + c.getDay()+ 日);tAddress.setText(c.getAddress();if (c.isType() lnew.setVisible(true);tNew.setText(c.toNewCode();tNew.setVisible(true);elselnew.setVisible(false);tNew.setVisible(false);/* *
36、清空面板上的身份信息。仅当身份证号为假时,调用。 */private void clear()tBirth.setText();tSex.setText();tType.setText();tAddress.setText();tNew.setText();八、运行效果九、思考题1Java程序中字符串常量使用什么类来表示?字符串变量又使用什么类来表示?它们主要区别在哪里?字符串常量用S突然那个类,变量用StringBuffer。内部都是用字符数组类保存字符串的,但是String的数组是用多少分配多少的数组大小,而StringBuffer的数组则比要用到的大小还要大一些。然后在字符串需要修改的时
37、候,StringBuffer直接修改自身,而不需要重新分配内存空间。而String则要创建新的字符串,再改变变量名引用的位置。2请说明程序String s1=I like ;s1+=Java!; 和程序StringBuffer s1=new StringBuffer(I like ); s1.append(Java!); 的区别。依据你得出的结论,如果程序需要处理大量的字符串连接操作,应该尽量使用String类还是StringBuffer类?第一段代码String s1=I like ;s1+=Java!;这段代码运行效率不如第二段代码。它完成的功能是,在常量池中创建一个字符串“I like ”。s1指向该位置。然后再在常量池中新建一个字符串“I like Java!”,然后让s1重新指向该位置。第二段代码StringBuffer s1=new StringBuffer(I like );s1.append(Java!);在堆去新建一个对象s1,它包含的字符串是“I like”(内部用字符数组来保存,但是长度略大),然后,在这个字符数组尾部添加新的字符串“Java!”大量的字符串连接应该用第二种。专心-专注-专业
限制150内