我有这个方法的问题。对于初学者来说,它会继续告诉我需要添加回报,我会在if else检查中添加回报。第二个问题是,根本不会循环。当我在if else语句之后添加一个返回值来测试循环(删除add返回错误)时,无论用户输入什么,它都会简单地遍历它。任何建议,将不胜感激。虽然循环如果其他语句不能正常工作
public static boolean newGame() {
// char variables for the user input
char yes = 'y';
char no = 'n';
// Request for user input
Scanner userInput = new Scanner(System.in);
System.out.println("Are you ready to play? Press \"y\" for Yes and \"n\" for No.");
// converts userInput to a char
String userChoice = userInput.nextLine();
char userChar = userChoice.charAt(0);
do {
// determines if the game starts or not
if (userChar == yes) {
System.out.println("GREAT!! Let's play!");
return true;
} else if (userChar == no) {
System.out.println("Thanks for playing!!");
return false;
} else {
System.out.println("Please enter \"y\" or \"n\"");
}
} while (userChar != yes || userChar != no);
}
循环是无限的,因为userChar在循环内部永远不会改变,如果你使它成为布尔值,你必须返回一个布尔值。 – ivan
在||中使用.equals和&&它总是真的 – Ctx
@Ctx'=='和'!='将在这里工作;值是'char'。 – rgettman