簡體   English   中英

如果用戶輸入無效選項,則請求相同的輸入

[英]Requesting the same input if user enters an invalid option

public static void main(String[] args) {
  int i = 0;
  while (i==0) { //game restarts if i=0
    PlayGame(); // Resets back to the start after the game is finished.

    System.out.print("Would you like to start again? (y/n) ");
    String sAns = System.console().readLine();
    if (sAns.equalsIgnoreCase("y")) { //! means other
       System.out.println("Restart");
       i=0; // make it so they cant do another letter//
    }
    else if (sAns.equalsIgnoreCase("n")) {
       System.out.println("");
       i=1;  // breaks the loop
    }
    else {
       System.out.println("Invalid input.");
       // loop it back to the question
    }
  }
}

好吧,問題是我想這樣做,所以如果他們輸入任何其他字符,例如 Z 或 Integer,它會說“無效的選項,請重試” 循環回到同一個問題“你想重新開始? (y/n)"

在我說出答案之前有一件事:你不需要為 0 和 1 創建一個int ,有一種稱為boolean的類型可以保持 false 或 true,它基本上類似於 0 和 1。

如果你想一次又一次地循環"Would you like to start again? (y/n) " ,你可以這樣做:

while(true) { // surround with while loop
System.out.print("Would you like to start again? (y/n) ");
  String sAns = System.console().readLine();
  if (sAns.equalsIgnoreCase("y")) {//! means other
    System.out.println("Restart");
    i=0;// make it so they cant do another letter//
    break;
  }
  else if (sAns.equalsIgnoreCase("n")) {
     System.out.println("");
    i=1;// breaks the loop
    break;
  }
  else {
    System.out.println("Invalid input.");
    //loop it back to the question
  }
}

如您所見, break語句可以輕松跳出循環。

將所有 if/if else/else 語句放在while (true)中。 如果輸入有效,使用break; 在 if 語句中。 在這種情況下,您不需要使用else語句。 如果兩個 if 語句都不為真,程序將繼續請求輸入。

您可以添加另一個while語句。

  public static void main(String[] args) {
  int i = 0;
  while (i==0) {//game restarts if i=0
    PlayGame();// Resets back to the start after the game is finished.

    boolean valid = false;
    while(!valid) {
      System.out.print("Would you like to start again? (y/n) ");
      String sAns = System.console().readLine();
      if (sAns.equalsIgnoreCase("y")) {//! means other
        System.out.println("Restart");
        i=0;// make it so they cant do another letter//
        valid = true;
      }
      else if (sAns.equalsIgnoreCase("n")) {
        System.out.println("");
        i=1;// breaks the loop
        valid = true;
      }
      else {
        System.out.println("Invalid input.");
        valid = true;
        //loop it back to the question
      }
    } 
  }
}

暫無
暫無

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

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