![](/img/trans.png)
[英]Java - How would I return an exception if the user enters a invalid input?
[英]Requesting the same input if user enters an invalid option
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 或 Integer,它会说“无效的选项,请重试” 循环回到同一个问题“你想重新开始? (y/n)"
在我说出答案之前有一件事:你不需要为 0 和 1 创建一个int
,有一种称为boolean
的类型可以保持 false 或 true,它基本上类似于 0 和 1。
如果你想一次又一次地循环"Would you like to start again? (y/n) "
,你可以这样做:
while(true) { // surround with while loop
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//
break;
}
else if (sAns.equalsIgnoreCase("n")) {
System.out.println("");
i=1;// breaks the loop
break;
}
else {
System.out.println("Invalid input.");
//loop it back to the question
}
}
如您所见, break
语句可以轻松跳出循环。
将所有 if/if else/else 语句放在while (true)
中。 如果输入有效,使用break;
在 if 语句中。 在这种情况下,您不需要使用else
语句。 如果两个 if 语句都不为真,程序将继续请求输入。
您可以添加另一个while
语句。
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.
boolean valid = false;
while(!valid) {
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//
valid = true;
}
else if (sAns.equalsIgnoreCase("n")) {
System.out.println("");
i=1;// breaks the loop
valid = true;
}
else {
System.out.println("Invalid input.");
valid = true;
//loop it back to the question
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.