Java自定义异常,抛出异常信息,通过异常提示,再继续进行输入成绩

package com.it.homework;
import java.util.Scanner;
public class TestInputPoints {
	static Scanner scan = new Scanner(System.in);
	public static void main(String[] args) {
		System.out.println("请先输入需要录入的学生的人数:");
		int n = scan.nextInt();
		int[] pointsArr = new int[n];
		for (int i = 0; i < pointsArr.length; i++) {
			System.out.println("请输入第"+(i+1)+"个学生的成绩:");
			int points = -1 ;
			while(true) {
				try {
					points = scanPoints();
				} catch (IllegalInputException e) {
					e.printStackTrace();
					System.out.println("请重新输入第"+(i+1)+"个学生的成绩:");
				}finally {
					if(points != -1) {
						pointsArr[i] = points;
						break;
					}
				}
			}
		}
		int sum = 0;
		for (int i = 0; i < pointsArr.length; i++) {
			sum+=pointsArr[i];
		}
		System.out.println("平均分是"+sum/(n*1.0));
		
	}
	public static int scanPoints() throws IllegalInputException {
		int points = scan.nextInt();
		if(points<0) {
			throw new IllegalInputException("分数不可为负数");
		}
		return points;
	}
}
class IllegalInputException extends Exception{
	
	public IllegalInputException() {}
	
	public IllegalInputException(String message) {
		super(message);
	}
}

在这里插入图片描述

发布了37 篇原创文章 · 获赞 29 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42755868/article/details/105027541