[英]How do I allow another attempt at an input
So I have this code 所以我有这段代码
import java.util.Scanner;
public class Test2{
public void myScanner () {
System.out.println("Do you want to have an adventure?");
System.out.println("1 for yes, 2 for no");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int answer = Integer.parseInt(input);
switch (answer) {
case 1: System.out.println("yes");
break;
case 2: System.out.println ("no");
break;
default: System.out.println("not valid answer");
}
}
}
And what I'm trying to figure out is how to allow another attempt at answering the question after a wrong answer is given. 我想找出的是在给出错误答案后如何允许再次尝试回答该问题。 So far, everything else works perfectly. 到目前为止,其他所有功能都可以正常运行。
Just invoke myScanner() function after default: statement 只需在default:语句后调用myScanner()函数
default: System.out.println("not valid answer");
myScanner();
Introduce a boolean variable called validAnswer
before you ask for input from the user. 在要求用户输入之前,引入一个名为validAnswer
的布尔变量。 Give it an initial value of false
. 给它一个初始值false
。
You can then wrap the section of your code that prompts for input from the user in a while
block, like so: 然后,您可以将代码段中提示用户输入的内容包装在while
块中,如下所示:
while(!validAnswer) {
String input = scanner.next();
//etc, etc.
}
You then need to modify your switch statement so that if the input is valid, set validAnswer
to true in addition to printing to the console - this should let you escape from the while
loop but keep the loop going if the input is invalid. 然后,您需要修改switch语句,以便在输入有效的情况下,除了打印到控制台外, validAnswer
设置为true -这应该使您从while
循环中退出,但如果输入无效,则使循环继续进行。
As you're learning: the basic way to do this is : 在学习时:实现此目的的基本方法是:
boolean exit;
do{
exit = true;
System.out.println("Do you want to have an adventure?");
System.out.println("1 for yes, 2 for no");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int answer = Integer.parseInt(input);
switch (answer) {
case 1: System.out.println("yes");
break;
case 2: System.out.println ("no");
break;
default: System.out.println("not valid answer");
exit = false;
}
} while(!exit);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.