定义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.
信仰是一束光,每个人寻着光而前行,哪怕会遇到荆棘险滩,也会秉持心中梦,固守脚小的路,坚韧向前。
千万不要在该奋斗的年龄选择安逸,当所有人都在奔跑的时候,怎么还能悠闲的散步?
要成为光,就成为光,我们的世界才能万丈光芒。