【发布时间】:2020-09-27 00:26:01
【问题描述】:
public static void main(String[] args) {
int i = 0;
while (i==0) { //game restarts if i=0
PlayGame(); // Resets back to the start after the game is finished.
System.out.print("Would you like to start again? (y/n) ");
String sAns = System.console().readLine();
if (sAns.equalsIgnoreCase("y")) { //! means other
System.out.println("Restart");
i=0; // make it so they cant do another letter//
}
else if (sAns.equalsIgnoreCase("n")) {
System.out.println("");
i=1; // breaks the loop
}
else {
System.out.println("Invalid input.");
// loop it back to the question
}
}
}
问题是我想这样做,所以如果他们输入任何其他字符,例如 Z 或整数,它会说“无效的选项,请再试一次” 循环回到同一个问题“你愿意重新开始?(y/n)"
【问题讨论】:
-
根据您的代码,您无需为此做任何事情。它会在说“无效输入”后自动返回循环,因为您没有更新 i 的值,循环将继续。