0

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;

                }
            }
RIDDLEisVoltron
  • 31
  • 1
  • 1
  • 5

2 Answers2

1

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

}
0

I assume you want the user to enter an integer 1-5 and proceed to the next question? If so, try this:

Replace:

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

With:

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