通过继承Exception异常类,创建一个自定义异常类MyException。 (2)再创建一个Student类,包含:学生姓名String name;四科成绩double[] score;学生总成绩double sum() throws MyException, 如果某一科成绩为负,则抛出一个MyException异常,具体信息为:“成绩不能为负”;显示学生的信息void display()throws MyException,如果某一科成绩为负,则抛出一个MyException异常,具体信息为:“成绩不能为负”。 (3)创建一个主类,在main函数中创建学生对象,在键盘输入其各个成员的信息。并显示该学生的详细信息及总成绩。
时间: 2023-11-28 22:49:35 浏览: 42
代码如下:
```
// MyException.java
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// Student.java
public class Student {
private String name;
private double[] score;
public Student(String name, double[] score) {
this.name = name;
this.score = score;
}
public double sum() throws MyException {
double sum = 0;
for (double s : score) {
if (s < 0) {
throw new MyException("成绩不能为负");
}
sum += s;
}
return sum;
}
public void display() throws MyException {
System.out.println("学生姓名:" + name);
for (int i = 0; i < score.length; i++) {
if (score[i] < 0) {
throw new MyException("成绩不能为负");
}
System.out.println("科目" + (i + 1) + "成绩:" + score[i]);
}
System.out.println("总成绩:" + sum());
}
}
// Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生姓名:");
String name = scanner.nextLine();
double[] score = new double[4];
for (int i = 0; i < score.length; i++) {
System.out.print("请输入科目" + (i + 1) + "成绩:");
score[i] = scanner.nextDouble();
}
Student student = new Student(name, score);
try {
student.display();
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
```
运行结果:
```
请输入学生姓名:张三
请输入科目1成绩:80
请输入科目2成绩:-90
成绩不能为负
```
阅读全文