-9

I'm doing a Java assignment in Greenfoot and I'm stuck on a question about getter and setter methods which I cannot find an answer to.

I'm asked to write a getter and setter method for three attributes (name, colour, age) and then use these methods to:

(a) ensure that age cannot be less than 0 and age cannot be greater than 100

(b) ensure the only valid colours are Black, White, Brown and Grey

Any ideas or suggestions to how I would solve this problem?

Thanks in advance

2 Answers2

1

I hope that help you, that will give you at least a visibility and you can modify it as you want :

public class MyClass {

    private String name;

    private int age;

    private String color;

    private final List<String> colors = Arrays.asList("Black", "White", "Brown ", "Grey");

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getColor() {
      return color;
    }

    public void setColor(String color) {
      if (colors.contains(color)) {
        this.color = color;
      } else {
        // if not valid do what you want
      }
    }

    public int getAge() {
      return age;
    }

    public void setAge(int age) {
      if (age > 0 && age <= 100) {
        this.age = age;
      } else {
        // if not valid do what you want
      }
    }

  }
Younes Ouchala
  • 300
  • 1
  • 4
  • 15
0

I see that there is already a very nice code answer to your question, so i will focus on explaning getter and setter methods:

getter methods are used to get an atribute (also known as a field.) An atribute is usualy found in the top a program, for instance: private int i; i is an atribute. atributes can be accesed by all methods in the same class. so when writing a getter method you simply have to write:

public returntype getSomeAtribute(){
    return someAtribute; 
}

setter methods are used to set the value of an atribute, different types of atributes can have different values, boolean has true or false, int has integers, String has text. to set the value of a you simply overwrite the current value by writing:

public void setSomeAtribute(){
   someAtribute = something; 
}