如何验证输入是否为 Int 且在数字范围内?

How to I validated an input for being an Int and within a number range?

程序显示一个问题,用户要输入一个数字 1 到 5。5 个问题供 5 个用户使用。但是,只要它是一个 Int,该程序就无法识别好的输入或坏的输入。在它再次运行 Survey.presentQuestions() 之前,我必须多次输入输入。我不知道为什么。

    for (int i = 0; i < 5; i++) 
            {
                for (int j = 0; j < 5; j++) 
                {
                    Survey.presentQuestion(j, i);
                    do{
                        TempAns = in.nextInt();
                        while (!(in.hasNextInt()))
                        {
                            System.out.println("Please enter integer value from 1 to 5!");
                            in.next();
                        }
                    }while(TempAns >= 1 && TempAns <= 5);
                    Survey.ResultArray[i][j] = TempAns;

                }
            }

我假设您希望用户输入 1-5 的整数并继续下一个问题?如果是这样,试试这个:

替换:

                    do{
                        TempAns = in.nextInt();
                        while (!(in.hasNextInt()))
                        {
                            System.out.println("Please enter integer value from 1 to 5!");
                            in.next();
                        }
                    }while(TempAns >= 1 && TempAns <= 5);

与:

while (true) {
            TempAns = in.nextInt();
            if (TempAns >= 1 && TempAns <= 5)
                return;
            else
                System.out.println("Please enter integer value from 1 to 5!");
        }

更新试试这个

 for (int i = 0; i < 5; i++) {
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            System.out.println("Student: "+(i+1)+" Grade: "+(j+1));
            System.out.println("Please enter integer value from 1 to 5!");
            TempAns = getNumber();
        }
    }

和另一种方法

 public int getNumber(){
    Scanner in =new Scanner(System.in);
    int validatedNumber;
    do{


    try{
        String toValidate=in.next();
        validatedNumber= Integer.parseInt(toValidate);
        if (validatedNumber>0 && validatedNumber<6){
            return validatedNumber;
        }else{
            System.out.println("Between 1 and 5!!");
        }
    }catch(Exception e){
        System.out.println("You have to chose a number!");
    }
    }while(true);

}