How to let the user input back to the former question

4313 views java
2

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");
       }
   }

answered question

Use a while loop with a condition

If you want your code to be able to "go back" and do something again, the "something" needs to be inside a loop.

1 Answer

13

while (true) {
        try {
            System.out.println("Input Cruise ID:");
            cruiseId = sc.nextInt();
            break;
        } catch (Exception e) {
            System.out.println("Please Enter integer:");
            sc.nextLine();
        }
    }

    System.out.println("Input ship name :");
    try{
        shipName = sc.next();
    }catch(Exception e){
        if( shipName.equalsIgnoreCase("Sydney1") || shipName.equalsIgnoreCase("Melmone1")){
            System.out.println("Oops!! We don't have this ship!! Please enter the ship name : Sydney1 or Melbone1");
        }
    }

posted this

Have an answer?

JD

Please login first before posting an answer.