无法解析java中的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22795894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot resolve method in java
提问by
I have a question object that has 4 answer objects inside.
我有一个问题对象,里面有 4 个答案对象。
In question.java I have a method that is:
在 question.java 我有一个方法是:
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 im not quiet sure why.
这给了我一个“无法解析方法 getA()”的错误,我不确定为什么。
For reference,
以供参考,
System.out.println(questions.get(randomNum));
works perfectly fine in printing out the question and the answers.
在打印问题和答案时效果很好。
Question.java
问题.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
答案.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;
}
}
回答by Josiah Hester
Make sure your container (using generics) holds the Question type:
确保您的容器(使用泛型)拥有问题类型:
ArrayList<Question> questions = new ArrayList<Question>();
That way JAVA knows which method to call.
这样 JAVA 就知道调用哪个方法。