Write a method setRating that reads a rating from the keyboard, insisting that the rating supplied by the user be valid.
rating should be 1 to 5;

public void setRating(){
    System.out.println("enter rating ");
    int myRating = keyboard.nextInt();
}

is this correct?

or need to include like this

public void setRating(){
    System.out.println("enter rating ");
    int myRating = keyboard.nextInt();
    while((rating >= 1) && (rating <= 5))
    {
      System.out.println("Error - rating not in range");
      System.out.println("enter rating again ");
      myRating = keyboard.nextInt();
    }
 }

Recommended Answers

All 5 Replies

... insisting that the rating supplied by the user be valid.
rating should be 1 to 5;

The first verion does not even try to do this, so it cannot be right.
The second version does, but it has a logic error in the if test, which you can fix easily
And you might want to set a variable that will survive after the end of your method

insisting that the rating supplied by the user be valid

This part is somewhat not sure for me (the language). Does it mean your program has to also validate the validity of the user input, or the user will always enter a valid input???

Re: JamesCherrill, thank you very much.
Logic error? you mean because of local variable or while condition?
I did not get it.

Re:Taywin, Thank you very much.
This is exactly what it appears in the textbook. It could be both ways but I get the meaning of program has to validate input, (for safe side)

Logic error: your syntax in the while is OK, but the way you have coded it will give you exactly the opposite of the result you wanted.

Thank you sir, I got it corrected with !.
You are awsome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.