Java自定義異常例題演示

  編寫一段程序,完善學生 student 類,增加輸入學生的成績的操作方法,如果小於 0 分或者大於 100 分則拋出異常,並捕捉異常,輸出提示信息:輸入的學生成績超出範圍了!

import java.util.Scanner;
class MyException extends Exception{
	public MyException(String msg) {
		super(msg);
	}
}
class Student{
	private String name;
	private int age;
	private int score;
	
	public void setScore(int score) throws Exception{
		if(score>0&&score<=100)
			this.score=score;
		else
			throw new MyException("輸入的學生成績超出範圍了!");
		
	}
	public String getScore(){
		if(score >= 60)
			return "考試成績及格";
		else if(score<60&&score!=0)
			return "考試成績不及格";
		else
			return "成績輸入錯誤!";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String toString(){
		return ("姓名:" + getName() +",年齡:" + getAge() + ",考試情況:" + getScore());
	}
	
}
public class Experiment {
	
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		Student student = new Student();
		student.setName("小張");
		student.setAge(22);
                System.out.print("輸入成績:");
		int score = sc.nextInt();
		try{
			student.setScore(score);
		}catch(MyException e){
			System.out.println(e.getMessage());
		}
		System.out.println(student);
		System.out.println("*****************");
	}
	
}

運行可能結果:

輸入成績:120
輸入的學生成績超出範圍了!
姓名:小張,年齡:22,考試情況:成績輸入錯誤!
*****************

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章