简体   繁体   中英

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. 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. 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. What you need is a while loop .

You can use a do-while loop as follows so that it runs first before performing a check:

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).

try-catch block are mainly used to handle exceptional cases. Try not to misuse it as a control statement for your implementations.

You can add more checks inside the while loop itself. 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();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM