一、实验目的
1.编写try-catch块处理异常
二、实验内容
1. 【NumberFormatException异常】编写一个程序,提示用户输入两个整数,然后显示它们的和。用户输入错误时提示用户重新输入。
2. 【ArrayIndexOutOfBoundsException异常】编写一个程序,创建一个由100个随机选取的整数构成的数组;提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。
3.【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
三、实验要求:
要求每个学生独立完成实验任务。
四、实验报告
1. 实验结果与分析
(1)NumberFormatException异常
A) 实验运行情况
首先根据提示输入两个数,每个数占一行
回车,如果输入的格式正确,回复结果
如果输入格式错误,提示输入错误并重新输入,直至两个数都输入正确
B) 结果分析
NumberFormatException异常在当字符串转换成整型而字符串格式错误时出现,是数字格式匹配的失误
因此首先设置两个String类型实例,代表两个字符串
String num1,num2;
这两个实例在输入后转换成整型时可能会抛出NumberFormatException异常
例如如果输入的内容无法转换则就会返回这个异常
(附测试代码)
package exp6;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
String string = new String();
Scanner input = new Scanner(System.in);
System.out.println("输入数字");
string = input.nextLine();
int num = Integer.parseInt(string);
System.out.println(num);
}
}
因此设置do-while语句,内部嵌套try-catch语句实现直到正确输入时才返回结果的程序,在try块中按照测试代码的方法设置可能异常语句,即可完成实验测试。
try{
System.out.println("请输入两个数:");
num1 = input.nextLine();
num2 = input.nextLine();
int sum = Integer.parseInt(num1.trim())+ Integer.parseInt(num2.trim());
System.out.println(num1 + " + "+ num2 +" = " + sum);
judge = false;
}
catch(NumberFormatException ex){
System.out.println("请输入两个有意义的数");
}
(2)ArrayIndexOutOfBoundsException异常
A) 实验运行情况
首先根据提示输入一个大于等于0,小于100的数组下标值
如果输入正确,返回该值下面的随机整数(1-500)
如果输入超出下标范围,输出错误并提示重新输入直至输入满足范围
B) 结果分析
ArrayIndexOutOfBoundsException异常如其字面意思,在数组越界的情况下会出现
因此设置一确定数组并随机赋值,输入一个越界值就可以返回这个异常
(附测试代码)
package exp6;
import java.util.Random;
import java.util.Scanner;
import org.omg.PortableInterceptor.IORInterceptor_3_0;
public class Test2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
for(int i = 0;i < 100;i++){
Random random = new Random(500);
num[i] = random.nextInt();
}
System.out.println("输入下标值");
int n = input.nextInt();
System.out.println(num[n]);
}
}
因此设置do-while语句,内部嵌套try-catch语句实现直到正确输入时才返回结果的程序,在try块中按照测试代码的方法设置可能异常语句,即可完成实验测试。
try{
System.out.println("请输入数组下标: ");
int index = input.nextInt();
System.out.println(index + "下标的数组元素值为 " +data[index]);
judge = false;
}
catch(IndexOutOfBoundsException ex){
System.out.println("数组越界!请重新输入!");
}
}
(3)OutOfMemoryError错误
A) 实验运行情况
首先根据提示输入数组大小
如果输入范围未超出虚拟机承受范围,则可以返回创建正确
否则返回创建失败并提示重新输入直到创建成功
B) 结果分析
OutOfMemoryError错误是错误的一种,属于免检异常的一种,当创建的数组大小超过虚拟机所承受范围就会返回这一错误
因此可以先输入一个长整型的比较大的数,然后创建数组时就会抛出这个异常
(附测试代码)
package exp6;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("输入大小");
long num = input.nextLong();
int[] tmp = new int[(int)num];
}
}
因此设置do-while语句,内部嵌套try-catch语句实现直到正确输入时才返回结果的程序,在try块中按照测试代码的方法设置可能异常语句,即可完成实验测试。
try{
System.out.println("请输入数组大小");
long num = input.nextLong();
long[] ls = new long[(int) num];
System.out.println("创建成功!");
jud = false;
}
catch(OutOfMemoryError ex){
System.out.println("创建失败");
2. 心得体会
本次的实验是新学的知识:异常处理,这在之前的C++语言中是没有接触过的,因此在写这块的程序的时候比较卡手,需要先查找每个异常或错误对应的类型和出现的情况并在程序的try块中实现对异常的抛出,在catch语句中实现处理,也因为这个原因,在写这块的代码的时候会对这块的东西印象更为深刻。同时对try-catch模式的代码有了更深的理解,实践出真知,在理论学习时总是以为自己听懂了,但只有在自己真的去实现和使用出现各种问题的时候才会对知识有更深一步的理解和记忆。
3.【附源程序】
(1)
Person.java
package exp5;
public class Person {
private String name;
private String telenum;
public String getName(){
return this.name;
}
public String getTeleNum(){
return this.telenum;
}
public void setName(String name){
this.name = name;
}
public void setTeleNum(String telenum){
this.telenum = telenum;
}
@Override
public String toString() {
return "Person类:姓名为" + this.getName() + " " + "电话为:" + this.getTeleNum();
}
}
Student.java
package exp5;
public class Student extends Person{
private String Grade;
public String getGrade(){
return Grade;
}
public void setGrade(String Grade){
this.Grade = Grade;
}
@Override
public String toString() {
return "Student类:姓名为" + this.getName() + " " + "电话为:" + this.getTeleNum() + " 年级为:" + this.getGrade();
}
public String displayObject(){
return "to " + this.getName() + ": 请按时交实验报告";
}
}
Employee.java
package exp5;
import java.sql.Date;
public class Employee extends Person{
private int salary;
private MyDate date;
public int getSalary(){
return salary;
}
public void setSalary(int salary){
this.salary = salary;
}
public String getDate(){
return date.getYear() + "," + date.getMonth() + "," + date.getDay();
}
public void setDate(MyDate date){
this.date = date;
}
@Override
public String toString() {
return "Employee类:姓名为" + this.getName() + " " + "电话为:" + this.getTeleNum() + " 工资为:"
+ this.getSalary() + " 受聘日期为:" + this.date.getDate() ;
}
public String displayObject(){
return "to " + this.getName() + ": 请按时上班";
}
}
MyDate.java
package exp5;
public class MyDate {
public MyDate(String year,String month,String day){
this.year = year;
this.month = month;
this.day = day;
}
private String year;
private String month;
private String day;
public String getYear() {
return year;
}
public String getMonth() {
return month;
}
public String getDay() {
return day;
}
public void setYear(String year) {
this.year = year;
}
public void setMonth(String month) {
this.month = month;
}
public void setDay(String day) {
this.day = day;
}
public String getDate(){
return this.year + this.month + this.day;
}
}
Test.java
package exp5;
public class Test {
static final String GradeOne = "One";
static final String GradeTwo = "Two";
static final String GradeThree = "Three";
static final String GradeFour = "Four";
public static void m1(Person p){
System.out.println(p.getName());
}
public static void m2(Person p){
System.out.println(p.toString());
}
public static void m3(Person p){
if(p instanceof Student){
System.out.println(((Student)p).displayObject());
}
else if(p instanceof Employee){
System.out.println(((Employee)p).displayObject());
}
else {
System.out.println("请求有误,请重新尝试!");
}
}
public static void main(String[] args) {
Person aPerson = new Person();
aPerson.setName("a");
aPerson.setTeleNum("12345");
Person bStudent = new Student();
bStudent.setName("b");
bStudent.setTeleNum("67890");
((Student)bStudent).setGrade(GradeOne);
Person cEmployee = new Employee();
cEmployee.setName("c");
cEmployee.setTeleNum("13579");
((Employee) cEmployee).setSalary(15000);
Employee employee = new Employee();
MyDate date = new MyDate("2011","09","05");
((Employee) cEmployee).setDate(date);
m1(aPerson);
m1(bStudent);
m1(cEmployee);
m2(aPerson);
m2(bStudent);
m2(cEmployee);
m3(aPerson);
m3(bStudent);
m3(cEmployee);
}
}
(2)
Course.java
package exp5;
import java.util.ArrayList;
public class Course {
private String courseName;
private ArrayList<String> students = new ArrayList<String>(100);
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students.add(numberOfStudents,student);
numberOfStudents++;
}
public ArrayList<String> getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
}
TestCourse.java
package exp5;
import java.util.ArrayList;
public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course("Data Structures");
Course course2 = new Course("Database Systems");
course1.addStudent("Peter Jones");
course1.addStudent("Brian Smith");
course1.addStudent("Anne Kennedy");
course2.addStudent("Peter Jones");
course2.addStudent("Steve Smith");
System.out.println("Number of students in course1: "
+ course1.getNumberOfStudents());
ArrayList<String>students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++)
System.out.print(students.get(i) + ", ");
System.out.println();
System.out.print("Number of students in course2: "
+ course2.getNumberOfStudents());
}
}
(3)
MyStack.java
package exp5;
import java.util.ArrayList;
import java.util.Scanner;
public class MyStack extends ArrayList{
public void push(Object o){
this.add(o);
}
public Object pop(){
Object o = this.get(this.size() - 1);
this.remove(this.size() - 1);
return o;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println("请输入元素的个数");
num = input.nextInt();
System.out.println("请输入元素: ");
MyStack myStack = new MyStack();
for(int i = 0; i < num;i++){
myStack.push(input.next());
}
for(int i = 0; i < num;i++){
System.out.println(myStack.pop());
}
}
}