[英]How to let the user input back to the former question
I write a code to let the user input cruise id first and then enter the ship name. 我编写了一个代码,让用户先输入游轮ID,然后输入船名。 At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
首先,我想检测用户是否输入了整数类型,否则,用户必须再次输入第一个问题。
But in my code, it will directly print the second question instead of go back to the first question and ask again. 但是在我的代码中,它将直接打印第二个问题,而不是返回第一个问题并再次询问。 Same, for the second question, I also want it return back and ask user to input again if the input is wrong
同样,对于第二个问题,我也希望它返回并请用户再次输入是否输入错误
Please help me for that. 请帮我。 Thanks!!
谢谢!!
try{
System.out.println("Input Cruise ID:");
sc1 = sc.nextInt();
}catch(Exception e){
System.out.println("Please Enter integer:");
sc.nextLine();
}
System.out.println("Input ship name :");
try{
sc2 = sc.next();
}catch(Exception e){
if( sc2 != "Sydney1" || sc2 !="Melmone1"){
System.out.println("Oops!! We don't have this ship!! Please enter the ship name : Sydney1 or Melbone1");
}
}
I write a code to let the user input cruise id first and then enter the ship name.
我编写了一个代码,让用户先输入游轮ID,然后输入船名。 At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
首先,我想检测用户是否输入了整数类型,否则,用户必须再次输入第一个问题。
What you need is an input validation. 您需要的是输入验证。
try-catch
block itself will not create an endless loop to reprompt the user should the input is not an integer. 如果输入不是整数,则
try-catch
块本身不会创建无限循环来提示用户。 What you need is a while loop
. 您需要的是
while loop
。
You can use a do-while
loop as follows so that it runs first before performing a check: 您可以使用以下
do-while
循环,以便在执行检查之前先运行它:
String input = ""; //just for receiving inputs
do{
System.out.println("Input Cruise ID:");
input = sc.nextInt();
}while(!input.matches("[0-9]+")); //repeat if input does not contain only numbers
int cruiseID = Integer.parseInt(input); //actual curiseID in integer
To perform validation for your second input (ie, your shipName, you need another while loop which encloses your prompt for input). 要对第二个输入(即您的shipName)执行验证,您需要另一个while循环,其中包含输入提示。
try-catch
block are mainly used to handle exceptional cases. try-catch
块主要用于处理特殊情况。 Try not to misuse it as a control statement for your implementations. 尽量不要将其误用作实现的控制语句。
You can add more checks inside the while loop itself. 您可以在while循环本身中添加更多检查。 For example, checking if the number is a negative number or zero etc. For example
例如,检查数字是负数还是零等。例如
while (true) {
try {
System.out.println("Input Cruise ID:");
cruiseId = sc.nextInt();
if(cruiseId <=0){
System.out.println("Please Enter integer:");
sc.nextLine();
}
break; // break when no exception happens till here.
} catch (Exception e) {
System.out.println("Please Enter integer:");
sc.nextLine();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.