user2540748
user2540748

Reputation:

Cannot resolve method in Java

I have a Question object that has 4 Answer objects inside.

In Question.java I have a method that is:

public Answer getA() {
    return a;
}

and in another method I have:

if (questions.get(randomNum).getA().isCorrect())
                System.out.println("Correct!");

where Questions is an ArrayList containing my Question objects.

This gives me a Cannot resolve method getA() error and I'm not quite sure why.

For reference:

System.out.println(questions.get(randomNum));

works perfectly fine in printing out the question and the answers.

Question.java

public class Question {
    private String questionText;
    private Answer a, b, c, d;

    public Question(String questionText, Answer a, Answer b, Answer c, Answer d) {
        this.questionText = questionText;
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

    public String getQuestionText() {
        return questionText;
    }

    public void setQuestionText(String questionText) {
        this.questionText = questionText;
    }

    public Answer getA() {
        return a;
    }

    public void setA(Answer a) {
        this.a = a;
    }

    public Answer getB() {
        return b;
    }

    public void setB(Answer b) {
        this.b = b;
    }

    public Answer getC() {
        return c;
    }

    public void setC(Answer c) {
        this.c = c;
    }

    public Answer getD() {
        return d;
    }

    public void setD(Answer d) {
        this.d = d;
    }

    public String toString() {
        return  questionText +
                "\nA) " + a +
                "\nB) " + b +
                "\nC) " + c +
                "\nD) " + d;
    }
}

Answer.Java

public class Answer {
    private String answerText;
    private boolean correct;

    public Answer(String answerText) {
        this.answerText = answerText;
        this.correct = false;
    }

    public String getAnswerText() {
        return answerText;
    }

    public void setAnswerText(String answerText) {
        this.answerText = answerText;
    }

    public boolean isCorrect() {
        return correct;
    }

    public void setCorrect() {
        this.correct = true;
    }

    public String toString() {
        return answerText;
    }
}

Upvotes: 5

Views: 62158

Answers (1)

Josiah Hester
Josiah Hester

Reputation: 6095

Make sure your container (using generics) holds the Question type:

ArrayList<Question> questions = new ArrayList<Question>();

That way Java knows which method to call.

Upvotes: 8

Related Questions