我有3个java程序
第一名:
public class Person{
private String firstname;
private String lastname;
private int g1;
private int g2;
private int g3;
private int periodic;
public Person(String firstname,String lastname,int periodic,int g1,int g2,int g3){
this.firstname = firstname;
this.lastname = lastname;
this.periodic=periodic;
this.g1=g1;
this.g2=g2;
this.g3=g3;
}
public void print(){
int a=(g1+g2+g3)/3;
System.out.println("\t"+ firstname + " "+ lastname);
System.out.println("Periodic Exam: " + periodic);
System.out.println("Grade of quiz 1: "+g1);
System.out.println("Grade of quiz 2: "+g2);
System.out.println("Grade of quiz 3: "+g3);
System.out.println("Average of the quizzes: "+a);
}
}
第二个:
public class Student extends Person{ //inherits Person//
public Student(String firstname,String lastname,int periodic,int g1,int g2,int g3){
super(firstname,lastname,periodic,g1,g2,g3);
}
public void print(){
System.out.println("Student Details:");
super.print();
}
}
第三个:
public class Main{
public static void main(String[] args){
Person persons[] = new Person[3];
persons[0] = new Student("Robert","Almazan",91,90,85,86);
persons[1] = new Student("Dennis","Navan",92,89,84,87);
persons[2] = new Student("Allan","Villariza",93,79,81,84);
for(Person person:persons){
person.print();
}
}
当我改变像这样的人时,我想做的就是捕捉异常
Person persons[] = new Person[3];
persons[0] = new Student("Robert","Almazan","ZZ",0,-85,86);
persons[1] = new Student("Dennis","Navan","ASA",0,-84,87);
persons[2] = new Student("Allan","Villariza","sa",0,-81,84);
我试过这样做
public class Main{
public static void main(String[] args){
try{
Person persons[] = new Person[3];
persons[0] = new Student("Robert","Almazan","ZZ",90,85,86);
persons[1] = new Student("Dennis","Navan","ASA",89,84,87);
persons[2] = new Student("Allan","Villariza","9",79,81,84);
for(Person person:persons){
person.print();
}
}//try
catch(ArithmeticException e){
System.out.println("Arithmetic Error");
}
catch(InputMismatchException e){
System.out.println("Input Error");
}
finally{
System.out.println("Thank you");
}
}//main
}
程序没有捕获异常
当我编译时,它仍然说像String这样的错误不能转换为int,它总是接受负数并且它不会捕获异常
需要帮助......
答案 0 :(得分:4)
您的代码:
persons[0] = new Student("Robert","Almazan","ZZ",0,-85,86);
^^^^
是编译时错误,因为您接受的第三个参数是int类型
public Student(String firstname,String lastname,int periodic,int g1,int g2,int g3){
^^^^^^^^^^^
您只能在运行时和时捕获异常,而不是在编译时。
答案 1 :(得分:1)
当我编译时,它仍然说像String这样的错误无法转换为 int,它总是接受负数而且它不会捕获异常
首先异常发生在运行时而不是编译时,因为您的程序有编译时错误,这是非常自我解释的,即String cannot be converted into int
。
问题是
new Student("Robert","Almazan","ZZ",0,-85,86);
/\
||
This is String not an int
但是你的学生类构造函数就像这样
public Student(String firstname,String lastname,int periodic,int g1,int g2,int g3)
/\
||
int not String
这就是为什么编译时错误即将来临,现在你的程序甚至没有成功编译,所以没有机会Exception直到你的程序运行。