Project 6 Java exception handling
Purpose
Understand the unique exception handling mechanism in the Java language; master the exception handling methods; correctly use the two exception handling methods of catching exceptions and declaring exceptions.
Experimental nature
Confirmatory experiment
Experiment content
(1) Analyze and debug the example of Section 4.5 in Chapter 4 of the textbook.
(2) Write a program: create a class Computer, which has a method to calculate the greatest common divisor of two integers. If the parameter of the method is negative, then Method throws a custom exception; verify the Computer class.
import java.util.Scanner;
public class Second {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("请输入第一个数:");
int x=in.nextInt();
System.out.print("请输入第二个数:");
int y=in.nextInt();
Computer calculate=new Computer();
try {
System.out.println("最大公约数为:"+calculate.CalculateTheMaximumCommonDivisor(x, y));
}catch(InputError e) {
System.out.println(e.getMessage());
}
}
}
class Computer{
Computer(){
}
public int CalculateTheMaximumCommonDivisor(int m, int n) throws InputError{
if(m<1||m<1) {
throw new InputError("只能输入自然数!");
}
if (m < n) {
// 保证被除数大于除数
int temp = m;
m = n;
n = temp;
}
while (m % n != 0) {
// 在余数不能为0时,进行循环
int temp = m % n;
m = n;
n = temp;
}
return n;
}
}
class InputError extends Exception{
public InputError(String string) {
super(string);
}
}
(3) Write a program, enter and display a batch of student information. Student information includes: student ID (integer type), name (string type), department number (integer value of 1-5). Requirements: The data entered by the user is incorrect, and the program throws an exception. (Customizable exception)
import java.util.Scanner;
public class Third {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入要学生人数:");
String num=in.nextLine();
int intnum=Integer.parseInt(num);
Student[] a=new Student[intnum];
int j=0;
for(int i=0;i<intnum;i++) {
j=0;
while(j==0) {
try {
System.out.print("请输入学号:");
String id=in.nextLine();
int intid=Integer.parseInt(id);
System.out.print("请输入姓名:");
String name=in.nextLine();
System.out.print("请输入部门:");
String number=in.nextLine();
int intnumber=Integer.parseInt(number);
a[i]=new Student(intid,name,intnumber);
j=1;
}catch(NumberError e) {
System.out.println("输入范围为1-5");
}
}
}
for(int i=0;i<intnum;i++) {
System.out.print(a[i].id+"\t"); System.out.print(a[i].name+"\t");
System.out.print(a[i].number+"\t"); System.out.println();
}
in.close();
}
}
class Student{
int id;
String name;
int number;
Student(int id,String name,int number)throws NumberError{
this.id=id;
this.name=name;
this.number=number;
if(number>5||number<1)
throw new NumberError();
}
}
class NumberError extends Exception{
}