重复一个方法
Repetition of a method
如果没有键入是或否,如果我想重复该方法,我将如何处理?我试过了:
while (!answer.equals("yes") && !answer.equals("no")) {
但它一直在输入 "please answer either yes or 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();
}
}
如果没有键入是或否,如果我想重复该方法,我将如何处理?我试过了:
while (!answer.equals("yes") && !answer.equals("no")) {
但它一直在输入 "please answer either yes or 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();
}
}