Renuz
Renuz

Reputation: 1667

How can i use a private method in a public method to check Validity?

    private boolean isValid(int aRating)
{                     

  return aRating >= 1 && aRating <= 10;

}

                or

    private boolean isValid(int aRating)
{                     

  if (aRating >=1 && aRating <=100
      return true;
  else
      return false

}

I now need to Write a method setRating(aRating) that sets the rating to aRating IF it is valid. So i am assuming that i need to use the method above in a public method to check if it is valid. If it is valid i then need to set rating = to aRating. So far my idea has been this:

    public void setRating(int aRating)
{
   if (isValid() == true)
       rating = aRating;

}

But i cannot use isValid as a == to true because it is a method. i also try using isValid(); in order to just try and use the method but it wont allow because of the (int aRating) at the top. If i do not have the identifier it then wont allow me to use aRating at all...

Now that it is

public void setRating(int aRating)
     {
       if (isValid(aRating))
          rating = aRating;
     }

I need to make a setRating() method that allows the user to input something from the keyboard and again it has to be valid, i keep getting an error because it says i cant overload SetRating(int aRating) Twice, which i understand. But if i try to take the int part out it is invalid because it needs a parameter. this is what i have

    public void setRating()
{
    Scanner keyboard = new Scanner(System.in);
  if (isValid(aRating))
      rating = keyboard.nextInt();
}

Upvotes: 1

Views: 752

Answers (2)

Roland Illig
Roland Illig

Reputation: 41686

You have to pass the aRating argument to the isValid method as well. And instead of just skipping the assignment for wrong values, it is often better to throw an exception, like this:

public void setRating(int rating) {
  checkRating(rating);
  this.rating = rating;
}

private void checkRating(int rating) {
  if (!(1 <= rating && rating <= 10)) {
    throw new IllegalArgumentException("Invalid rating: " + rating);
  }
}

This style of argument checking is used by popular classes like java.util.ArrayList, for example in the get(int) method.

Upvotes: 0

Corey Sunwold
Corey Sunwold

Reputation: 10254

public void setRating(int aRating)
{
   if (isValidRating(aRating))
       this.rating = aRating;
}

This might not be required for your homework, but in the real world you may also want to consider throwing an IllegalArgumentException if validation fails.

Example:

public void setRating(int aRating)
{
    if (isValidRating(aRating))
        this.rating = aRating;
    else 
        throw new IllegalArgumentException("Invalid rating.");
}

Upvotes: 2

Related Questions