javainputvalidating

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


The program displays a question and the user is meant to input a number 1 to 5. 5 questions for 5 users. However, the program doesn't recognize a good input, or a bad, as long as its an Int. I have to enter input a bunch of times before it goes it runs Survey.presentQuestions() again. I can't figure out why.

    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;

                }
            }

Solution

  • Update try this instead

     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();
            }
        }
    

    and this other method

     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);
    
    }