如何在一行中调用方法两次?



我有一个代码,在我的类中,我希望能够像qns.answer(5).answer(7)一样两次调用方法答案。但是现在,当我调用下面的方法answer时,我得到了错误不能找到symbol.

例如:

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);
}
}

如果您能给一些关于如何解决这个问题的建议,我将不胜感激。

Question可以有一个额外的字段来存储答案,您也可以编写一个新的构造函数来初始化该字段。

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);
}

那么在answer方法中,您可以返回一个新的Question,指定的答案为currentAns:

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

现在您可以链接多个ans调用。如果在它的末尾调用toString(无论是隐式的还是显式的),您可以得到所需的字符串。

在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.

如果你想在一个对象上多次调用相同或不同的方法(=链接)),则需要在方法中返回this

既然你想要达到的目标真的不清楚,我将提出一些建议:

class Question {
private final String question;
private final int correctAns;
private static String format(String quest, int ans) {
return String.format("%s: My answer is %d.", quest, ans);
}
public Question(String question) {
this.question = question;
this.correctAns = 0;
}
public String answer(int myAns) {
this.correctAns = myAns;
System.out.println("" + this);
return this;
}
@Override
public String toString() {
return format(this.question, this.correctAns);
}
}

这样你就可以在链中调用answer(),因为它返回对象本身(this)。

相关内容

  • 没有找到相关文章

最新更新