Noah Skull Weijian
Noah Skull Weijian

Reputation: 129

Getter and setter problems

I am new here and new in Java. I have an assignment in Java and this is the question:

The class should have the following methods:

  1. A constructor without arguments that initializes the name to "unknown", the urea and protein levels to 0.0 and the bleedingHistory value to false.
  2. A constructor that receives arguments for name and bleeding history and initializes the urea level and protein level to 0.0.
  3. Getters for all the instance variables
  4. Setters for all the instance variables, with validation for the following:

    • name cannot be blank

    • urea level must be between 0 and 10, inclusive

    • protein level must be between 0 and 150, inclusive

If any of the values passed in to the setters are invalid, then do not change the value of the instance variable and return false.

This is the instances variable:

public class Patient {

    private String name;
    private boolean bleedingHistory = true;

    private double ureaLevel;
    private double proLevel;

So my question is how to return to the instance variable above if the input value is not correct.

Upvotes: 0

Views: 438

Answers (1)

Mitch Talmadge
Mitch Talmadge

Reputation: 4765

It's simple, just make sure your setters have if-statements in them that validate the input. If the validation fails, don't change the variable at all; instead, throw an IllegalArgumentException to let the caller know that the name was unchanged. (Credit: @ADTC)

For example, here is the setter for the patient's name:

public void setName(String newName)  throws IllegalArgumentException
{
    if(newName != null && !newName.isEmpty()) 
    {
        this.name = newName;
    } 
    else 
    {
        throw new IllegalArgumentException();
    }
}

What the if-statement is evaluating is: "if newName is not null, and newName is not empty, then we will replace this.name with newName. Otherwise, we will throw a new IllegalArgumentException()."

Notice how if the if-statement evaluates to true, the variable name is replaced with newName, however, if it evaluates to false, we throw an IllegalArgumentException. If you were to call this method in your code, it should be called inside of a try-catch statement, like so:

try
{
    setName("John Doe");
}
catch(IllegalArgumentException e)
{
    //Name was not changed. Either it was null, or it was empty.
}

Upvotes: 2

Related Questions