定義Student類,含數據成員:name(姓名,String類型)、Score(成績,整型),定義一個異常類:InvalidScore類當Score<0或>100時產生異常拋出。
編寫主類程序測試你的定義:錄入學生姓名和成績生成Sudent對象數組(可以使用ArrayList<>),當姓名錄入爲Null時終止錄入;
錄入要求:當成績錄入異常時拋出InvalidScore異常並要求重新錄入成績。
其他需要定義的方法自行確定,達到上述目的即可。
java異常處理的知識可以參考菜鳥教程:https://www.runoob.com/java/java-exceptions.html.
運行預覽如下:
話不多說了,直接上代碼:
Studentmessage類:
package num;
public class Studentmessage {
String name ;
int Score;
Studentmessage(String name){
this.name = name;
}
public void setScore(int grade) throws InvalidScore{
if(grade<0||grade>100)
throw new InvalidScore(this.name+"成績無效,請重新輸入!");
else Score = grade;
}
public String toString() {
return "姓名: "+name+" 成績: "+Score;
}
}
InvalidScore類:
package num;
public class InvalidScore extends Exception{
InvalidScore(String message){
super(message);
}
public String toString() {
return this.getMessage();
}
}
InvalidScoremain類:
package num;
import java.util.*;
public class InvalidScoremain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
ArrayList<Studentmessage> Students = new ArrayList<>();
String name=null;
while(!(name = scan.next()).equals("null"))
{
Students.add(new Studentmessage(name));
do{
try
{
int grade = scan.nextInt();
Students.get(Students.size()-1).setScore(grade);
break;
}
catch (InvalidScore e)
{
System.out.println(e);
}
}while(true);
}
scan.close();
System.out.println("成績表: ");
for(Studentmessage s:Students)
{
System.out.println(s);
}
}
}
後記:
只要你要、只要我有。傾我所能、盡我所有。我給過你的,給不了第二個人。你給過我的,也請不要再給第二個人。
As long as you want, as long as I have. Pour all I can, do my all. I gave you, for a second.
信仰是一束光,每個人尋着光而前行,哪怕會遇到荊棘險灘,也會秉持心中夢,固守腳小的路,堅韌向前。
千萬不要在該奮鬥的年齡選擇安逸,當所有人都在奔跑的時候,怎麼還能悠閒的散步?
要成爲光,就成爲光,我們的世界才能萬丈光芒。