자바 사용자 정의 예외 메시지 입력 결과를 계속 한 후 이상이 프롬프트에 의해 발생하고,

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 ·은 10000 +를 볼

추천

출처blog.csdn.net/qq_42755868/article/details/105027541