如果我想重复该方法,如果没有输入 yes 或 no,我该怎么做?我尝试过:
while (!answer.equals("yes") && !answer.equals("no")) {
但它只是一直输入“请回答是或否”,而没有提供再次写入的选项。
谢谢
import acm.program.*;
public class YesOrNoQuestion extends ConsoleProgram {
public void run() {
println("This program asks you whether you want instructions");
String answer = readLine("Type your answer here: ");
YesOrNo(answer);
}
private void YesOrNo(String answer) {
if (answer.equals("yes")) {
println("Alright here you go");
} if (answer.equals("no")) {
println("Alright fine");
} else println("Please type either yes, or no: ");
}
}
最佳答案
- 您缺少
else if
!! - 此外,使用
String::toLowerCase()
将用户输入转换为小写得到NO
、nO
、No
和no
。 - 要在控制台中打印,请使用
System.out.println()
private void YesOrNo(String answer) {
if (answer.toLowerCase.equals("yes")) {
System.out.println("Alright here you go");
} else if (answer.toLowerCase.equals("no")) {
//↑ here!!!
System.out.println("Alright fine");
} else {
System.out.println("Please type either yes, or no: ");
run();
}
}
关于java - 方法的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32499969/