1

I am trying to add the following scanner validation as follows;

public void promptFilmRating() {
    while (!filmScanner.hasNextInt()) {
        System.out.println("Please enter a number instead of text.");
        filmScanner.next();
    }
    while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {
        System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
        filmRatingOutOfFive = filmScanner.nextInt();
    }

}

However when using the code that relates to the integer between value validation, repeated inputs are needed in order to record the original input and I am unsure on how to correct this, any advice would be fantastic.

1
  • store it into a variable? Commented May 4, 2018 at 21:50

2 Answers 2

1

I believe your problem is in while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {. Every call to filmScanner.nextInt() asks the stream for a new integer, so by calling .nextInt() twice in the while statement, you are asking for two numbers.

You might want to consider combining your two loops into one. Example:

int myNum;
do {
    myNumb = filmScanner.nextInt();
} while (myNum > 5 || myNum < 1);
Sign up to request clarification or add additional context in comments.

Comments

1

Store the value that you are getting in a variable, and use that variable to perform the checks.

Here is an example:

private void promptFilmRating() {

    Scanner filmScanner = new Scanner(System.in);
    int filmRatingOutOfFive;

    do{
        System.out.println("Please enter your rating for the film:");
        filmRatingOutOfFive = filmScanner.nextInt();

        if(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1)
            System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");

    }while(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1);


    System.out.println("You rated this film: "+filmRatingOutOfFive+" out of 5");


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.