(1)通过继承Exception异常类,创建一个自定义异常类MyException。 (2)再创建一个Student类,包含:学生姓名String name;四科成绩double[] score;学生总成绩double sum() throws MyException, 如果某一科成绩为负,则抛出一个MyException异常,具体信息为:“成绩不能为负”;显示学生的信息void display()throws MyException,如果某一科成绩为负,则抛出一个MyException异常,具体信息为:“成绩不能为负”。 (3)创建一个主类,在main函数中创建学生对象,在键盘输入其各个成员的信息。并显示该学生的详细信息及总成绩。2种写法
时间: 2024-02-15 09:02:24 浏览: 38
第一种写法:
MyException.java
```java
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
```
Student.java
```java
import java.util.Scanner;
public class Student {
private String name;
private double[] score;
public Student() {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生姓名:");
name = scanner.nextLine();
score = new double[4];
for (int i = 0; i < score.length; i++) {
System.out.print("请输入第" + (i + 1) + "科成绩:");
score[i] = scanner.nextDouble();
if (score[i] < 0) {
try {
throw new MyException("成绩不能为负");
} catch (MyException e) {
System.out.println("第" + (i + 1) + "科成绩输入有误:" + e.getMessage());
System.exit(0);
}
}
}
}
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);
System.out.print("四科成绩:");
for (double s : score) {
if (s < 0) {
throw new MyException("成绩不能为负");
}
System.out.print(s + " ");
}
System.out.println();
System.out.println("学生总成绩:" + sum());
}
}
```
Main.java
```java
public class Main {
public static void main(String[] args) throws MyException {
Student student = new Student();
student.display();
}
}
```
第二种写法:
MyException.java
```java
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
```
Student.java
```java
import java.util.Scanner;
public class Student {
private String name;
private double[] score;
public Student() {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生姓名:");
name = scanner.nextLine();
score = new double[4];
for (int i = 0; i < score.length; i++) {
System.out.print("请输入第" + (i + 1) + "科成绩:");
score[i] = scanner.nextDouble();
}
}
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);
System.out.print("四科成绩:");
for (double s : score) {
if (s < 0) {
throw new MyException("成绩不能为负");
}
System.out.print(s + " ");
}
System.out.println();
System.out.println("学生总成绩:" + sum());
}
}
```
Main.java
```java
public class Main {
public static void main(String[] args) {
Student student = new Student();
try {
student.display();
} catch (MyException e) {
System.out.println("输入有误:" + e.getMessage());
}
}
}
```
阅读全文