簡體   English   中英

如何讓用戶輸入回前一個問題

[英]How to let the user input back to the former question

我編寫了一個代碼,讓用戶先輸入游輪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");
       }
   }

我編寫了一個代碼,讓用戶先輸入游輪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塊主要用於處理特殊情況。 盡量不要將其誤用作實現的控制語句。

您可以在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();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM