Search code examples
javagetter-setterinstance-variables

How to use 1 setter for multiple instance variables


So, I am trying to create one setter method for multiple instance variables of one constructor. I have already made a getter that works this way:

public int getQuiz(int num) {

    int quiz = -1;
    int[] tempArray = {this.qz1, this.qz2, this.qz3, this.qz4, this.qz5};

    if(num != 0) {
        quiz = tempArray[num - 1];
    }
    else quiz = tempArray[num];

    return quiz;
}

Here the method has in its arguments the number of the quiz (qz) variable whose value it is supposed to return (the setter would, of course, have two args: int num and int score). The method is meant to work from 1, but if I forget that, I do not want an error if I ask for quiz 0, so that is the purpose of the if else.

This approach, however, will not work for a setter, as the array only contains the values of the instance variables, so changes to the array would not project into the instance variables. I am aware that this could be done with several if statements, I am just looking for a more elegant solution if there is one.

This is the constructor and the instance variables:

private String Name;
private int qz1, qz2, qz3, qz4, qz5;

Student(String Name, int qz1, int qz2, int qz3, int qz4, int qz5) {
    this.Name = Name;
    this.qz1 = qz1;
    this.qz2 = qz2;
    this.qz3 = qz3;
    this.qz4 = qz4;
    this.qz5 = qz5;
}

If you think that anything could be done better in the getter method please let me know as well.

Thank you for your answers!


Solution

  • I would suggest to make an int array to store your variables, so instead of: private int qz1, qz2,.... do

    private int [] quizValues;
    

    You can then get a value for a quiz:

    public int getQuizValue(int storePositionOfQuiz) {
      // check for outOfBounds!
      return this.quizValues[storePositionOfQuiz];
    }
    

    If you want you can then initialize the quiz values with using a int-array as parameter

    public void setQuizValues(int [] newValues) {
      this.quizValues = newValues;
    }