【发布时间】:2023-04-01 08:04:01
【问题描述】:
我有一个代码,在我的课堂上,我希望能够像qns.answer(5).answer(7) 一样两次调用方法答案。但是现在当我如下调用方法答案时,我得到错误找不到符号。
例如:
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);
}
}
如果您能就如何解决这个问题提供一些指示,我们将不胜感激。
【问题讨论】:
-
你指的是方法改变。你需要你的 answer 方法来返回一个问题对象
-
但是你最终想要的无法实现,因为第一种方法总是会打印它的输出,这意味着你将有两个打印语句和两个输出。