gpt4 book ai didi

java - 谓词方法在是/否/否则回答不回答的情况下返回重复提示

转载 作者:行者123 更新时间:2023-12-01 07:52:42 26 4
gpt4 key购买 nike

我目前正在关注 Erik Roberts 所著的《Java 的艺术与科学》一书。当在代码中测试是/否/替代答案时,我会因为没有答案而被问两次。

/*
* File: YesNoQuestion.java
* ------------------------
* This program asks the user a question and expects a yes / no
* answer. It is also exercise 7 in Chapter 5.
* "Write a predicate method askYesNoQuestion(prompt) that prints
* the string prompt as a question for the user and then waits
* for a response. If the user enters the string "yes", the
* askYesNoQuestion method should return true; if the user enters
* "no", the method should return false. If the user enters
* anything else, askYesNoQuestion should remind the user that it
* is seeking a yes-or-no answer and then repeat the question."
*/

import acm.program.*;

public class YesNoQuestion extends ConsoleProgram {

public void run () {
String prompt = "Are you over 18 year old?";
if (askYesNoQuestion(prompt) == true) {
println("Evaluated true.");
}
else if (askYesNoQuestion(prompt) == false) {
println ("Evaluated false");
}
}
/* Predicate method returns true if user enters the string "yes"
* and false if the user enters "no", else informs user that it is
* expecting a yes or no answer.
*/
private boolean askYesNoQuestion(String prompt) {
String userInput = readLine(prompt);
boolean trueOrFalse = true;
while(true) {
if (userInput.equalsIgnoreCase("yes")){
trueOrFalse = true;
break;
}
else if (userInput.equalsIgnoreCase("no")) {
trueOrFalse = false;
break;
}
else {
println("Please answer yes or no");
userInput = readLine(prompt);
}
}
return trueOrFalse;
}
}

这是输出的屏幕截图。谁能帮我理解为什么? Screenshoted output

最佳答案

在此代码中:

if (askYesNoQuestion(prompt) == true) {
println("Evaluated true.");
}
else if (askYesNoQuestion(prompt) == false) {
println ("Evaluated false");
}

我们可以看到您调用了 askYesNoQuestion(prompt) 两次。每次您调用它时,它都会提出问题并从用户那里得到另一个响应。

只需调用一次:

if (askYesNoQuestion(prompt) == true) {
println("Evaluated true.");
} else {
println("Evaluated false.");
}

如果 if 条件不匹配,则该方法一定返回 false,因此无需再次调用该方法并获取另一个结果。

此外,在语句中测试 boolean 值的正常方法如下:

if (askYesNoQuestion(prompt)) {
...

==true 部分是多余的。

关于java - 谓词方法在是/否/否则回答不回答的情况下返回重复提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34631110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com