Skip to content
Advertisement

How to call a method twice in a row?

I have a code where in my class I would like to be able to call the method answer twice like qns.answer(5).answer(7). But right now when I call the method answer as below, I get the error cannot find symbol.

For example:

Question qns = new Question("How many apples are there in the bag?")
qns ==> How many apples are there in the bag?: My answer is 0.

qns.answer(12)
==> How many apples are there in the bag?: My answer is 12.

qns.answer(12).answer(4)
==> How many apples are there in the bag?: My answer is 4.

qns
qns ==> How many apples are there in the bag?: My answer is 0.
class Question {
    private final String question;
    private final int correctAns;

    public Question(String question, int correctAns) {
        this.question = question;
        this.correctAns = correctAns
    }

    public String answer(int myAns) {
        return String.format("%s: My answer is %d.", this.question, myAns);
    }

    @Override
    public String toString() {
        return String.format("%s: My answer is 0.", this.question);
    }
}

Would appreciate if you could kindly give some pointers on how to get around this.

Answer

Question can have an extra field to store the answer, and you can also write a new constructor to initialise that field.

private final int currentAns;

public Question(String question, int correctAns, int currentAns) {
    this.question = question;
    this.correctAns = correctAns;
    this.currentAns = currentAns;
}

public Question(String question, int correctAns) {
    this(question, correctAns, 0);
}

// toString can now use currentAns!
@Override
public String toString() {
    return String.format("%s: My answer is %d.", this.question, currentAns);
}

Then in the answer method, you can return a new Question with the specified answer as currentAns:

public Question answer(int myAns) {
    return new Question(question, correctAns, myAns);
}

Now you can chain multiple ans calls. If toString is called at the end of it (whether implicitly or explicitly), you can get the desired string.

Example in JShell:

jshell> Question qns = new Question("How many apples are there in the bag?", 1);

qns ==> How many apples are there in the bag?: My answer is 0.

jshell> qns.answer(12);
$7 ==> How many apples are there in the bag?: My answer is 12.

jshell> qns.answer(12).answer(4);
$8 ==> How many apples are there in the bag?: My answer is 4.

jshell> qns
qns ==> How many apples are there in the bag?: My answer is 0.
Advertisement