编写一个程序,输入某个班某门课程成绩,统计及格人数和不及格人数的平均分。设计一个异常类,当输入成绩小于0或者大于100是抛出异常,程序将捕获这个异常,并作出相应处理。
直接贴程序
异常类定义:
class ScoreException extends Exception{
public ScoreException(String message){
super(message);
}
}
成绩处理类:
public class ScoreStatistics {
/**
* 及格线
*/
public static Integer PASSLIMIT = 60;
public static void main(String[] args) throws ScoreException {
Scanner scanner = new Scanner(System.in);
// 定义list存储所有成绩
List<Integer> scoreList = new ArrayList<>();
System.out.println("请录入班成绩,回车键录入下一个,输入00结束:");
while (true){
String next = scanner.next();
Integer score;
// 结束标志
if ("00".equals(next)){
break;
}else{
try {
// 类型转换,转换异常则说明录入格式不正确
score = Integer.valueOf(next);
}catch (Exception e){
System.out.println("输入数据类型不正确,请重新输入:");
continue;
}
}
if (score < 0 || score > 100){
throw new ScoreException("录入成绩需小于0或者大于100!");
}else {
scoreList.add(score);
}
}
// 输入完成后计算
averageScore(scoreList);
}
/**
* 计算平均分
* @param allScore 成绩list
*/
public static void averageScore(List<Integer> allScore){
if(CollectionUtils.isEmpty(allScore)){
return;
}
// 及格平均分
int passScore = 0;
// 及格分数List
List<Integer> passList = new ArrayList<>();
// 不及格平均分
int notPassScore = 0;
// 不及格List
List<Integer> notPassList = new ArrayList<>();
allScore.forEach(score ->{
// 大于等于及格线
if (score >= PASSLIMIT){
passList.add(score);
}else {
notPassList.add(score);
}
});
// 及格总分
for (Integer score : passList) {
passScore = passScore + score;
}
if (!CollectionUtils.isEmpty(passList)){
System.out.println("及格人数:" + passList.size() + ",及格人数的平均分:" + passScore/passList.size() );
}
// 不及格总分
for (Integer score : notPassList) {
notPassScore = notPassScore + score;
}
if (!CollectionUtils.isEmpty(notPassList)){
System.out.println("不及格人数:" + notPassList.size() + ",不及格人数的平均分:" + notPassScore/notPassList.size() );
}
}
}
class MyException extends Exception{
String message;
public MyException(int score){
message = "输入错误,分数应该在 0-100.";
}
}
public class Demo{
public static void main(String[] args) throws MyException {
Scanner in=new Scanner(System.in);
System.out.println("请输入成绩:");
int score=in.nextInt();
try {
new MyException(score);
}
catch(MyException e) {
System.out.println(e.message);
}
}
}