我编写了一个代码,让用户先输入巡航ID,然后输入船名。 首先,我想检测用户是否输入了整数类型,否则,用户必须再次输入第一个问题。
但是在我的代码中,它将直接打印第二个问题,而不是返回第一个问题并再次询问。同样,对于第二个问题,我也希望它返回并请用户再次输入是否输入错误
为此请帮帮我。谢谢!
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");
}
}
答案 0 :(得分:0)
我编写了一个代码,让用户先输入巡航ID,然后输入船名。首先,我想检测用户是否输入了整数类型,否则,用户必须再次输入第一个问题。
您需要的是输入验证。 try-catch
会自行阻止 ,如果输入的内容不是整数,则会创建一个无限循环来提示用户。您需要的是while loop
。
您可以按以下方式使用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
要对第二个输入(即您的shipName)执行验证,则需要另一个while循环,其中包含输入提示。
try-catch
块主要用于处理特殊情况。尽量不要将其误用作实现的控制语句。
答案 1 :(得分:-1)
您可以在while循环本身中添加更多检查。例如,检查数字是负数还是零等。例如
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();
}
}