簡體   English   中英

Java 錯誤的用戶輸入循環直到正確為止

[英]Java Wrong User Input Loop until correct

我在驗證程序時遇到問題。 我試過使用,While/Switch 但它都是一樣的。 問題是當用戶輸入錯誤的輸入時,例如 5,它會顯示錯誤,然后讓他們再次輸入,但如果他們再次輸入錯誤的數字,程序將不會驗證。 我絕對可以在其中一次又一次地復制代碼,但應該有更簡單的方法。

我希望你明白我想要達到的目標。

我怎樣才能使它成為一個繼續循環?

// Choosing the right room
public static int rooms () {
    int room;

    // Creating a new keyboard input
    Scanner scanner = new Scanner(System.in);
    // Displaying a message on the screen
    System.out.println("What room are you in? ");
    // Input
    room = scanner.nextInt();

    if (room==1) {
        roomOne();
    } else if (room==2) {
        roomTwo();
    } else if (room==3) {
        roomThree();
    } else if (room==4) {
        roomFour();
    } else {
        System.out.println("Wrong room number, please enter the room number.");
        room = scanner.nextInt();
    }

    //System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");    

    return room;
} // End Rooms

你正在尋找一個 while 循環,像這樣。

我使用 do ... while至少執行一次該行。

如果這不正確,這些方法會檢查值並打印一條消息。 返回 false 將阻止代碼退出循環並再次讀取。

{
     // Creating a new keyboard input
    Scanner scanner = new Scanner(System.in);


   int room;   
   do {
      // Displaying a message on the screen
      System.out.println("What room are you in? ");
      room = scanner.nextInt();
   } while( !isValid(room) );

   ... //if else or switch
}

private boolean isValid(int room){
   if(room > 4 || room  < 1){
       System.out.println("Try again ;)" );
       return false;
   }  else return true;
}

這是一個快速的代碼注釋甚至測試。

while (true) {
    int room = scanner.nextInt();
    if(room < 1 || room > 4) {
        System.out.println("Wrong room number, please enter the room number.");
        continue;
    }
    break;
}
if (room == 1) 
    roomOne();
else if (room == 2) 
    roomTwo();
else if (room == 3) 
    roomThree();
else if (room == 4) 
    roomFour();

希望它有所幫助,不過你應該多讀一點關於循環的內容。

這是您應該如何設置用於輸入清理的循環:

  1. 定義一個布爾值並分配一個真值或假值
  2. 使 while 循環在布爾值上運行
  3. 當輸入為“干凈”時,將布爾值設置為 true

暫無
暫無

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

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