文字型が入力されたときに"数字を入力してください"と出力できるようにしたい。

前提

成績の個数と点数を入力して、入力された点数を再度出力するプログラムです。
例外(負の数、文字、100点以上の点数)が発生した際に特定のエラー文を出力したいのですが、最初の成績の個数を入力する際に文字を入力すると、永遠にループしてしまいます。

実現したいこと

ループせずに、最初の成績の個数の入力に戻れるようにしたい。

エラーコード

何個の成績を入力しますか? a 数字を入力してください。 何個の成績を入力しますか? 数字を入力してください。 何個の成績を入力しますか? 数字を入力してください。 何個の成績を入力しますか? 数字を入力してください。 何個の成績を入力しますか? 数字を入力してください。 何個の成績を入力しますか? 数字を入力してください。 何個の成績を入力しますか? 数字を入力してください。 .....

このようにループしてしまう。

該当のソースコード

import java.util.InputMismatchException; import java.util.Scanner; public class HW1_2 { static int score[]; //成績 public static void main(String args[]) { try (Scanner scan = new Scanner(System.in)) { boolean check = true; while(check) { try { System.out.println("何個の成績を入力しますか?"); int num = scan.nextInt(); inputScores(num); outputScores(); check=false; } catch(NegativeArraySizeException e) { System.out.println("負の数を入力しました。"); } catch(InputMismatchException e) { System.out.println("数字を入力してください。"); } catch(Exception e) { System.out.println("範囲外の入力です。"); }//try-catch end }//while end } }//main end public static void inputScores(int arrSize)throws Exception{ score = new int[arrSize]; int i; System.out.println("成績を入力してください。"); Scanner scan = new Scanner(System.in); for(i=0; i<score.length; i++) { score[i] = scan.nextInt(); if((score[i]<0)||(score[i]>100)) { throw new Exception(""); } } }//inputScores end public static void outputScores() { System.out.println("+++++++++++++++++++++++++++++++"); System.out.println("成績公開"); for(int i=0; i<score.length; i++) { System.out.println((i+1)+"."+score[i]+"点"); } }//outputScores end }

コメントを投稿

0 コメント