簡體   English   中英

循環用戶輸入,直到滿足條件

[英]Loop user input until conditions met

我需要讓用戶輸入一個數字來用作范圍的開始,然后輸入另一個數字作為范圍的結束。 起始編號必須為0或更大,終止編號不能大於1000。兩個數字都必須被10整除。我找到了滿足這些條件的方法,但是如果不滿足這些條件,我的程序只會告訴用戶他們的輸入不正確。 我是否可以對其進行編碼,以便在用戶輸入后檢查是否滿足條件,如果條件沒有環回,請再次輸入。 這是我到目前為止的代碼。

    Scanner keyboard = new Scanner(System.in);
    int startr;
    int endr;
    System.out.println("Enter the Starting Number of the Range: ");
    startr=keyboard.nextInt();
    if(startr%10==0&&startr>=0){
        System.out.println("Enter the Ending Number of the Range: ");
        endr=keyboard.nextInt();
        if(endr%10==0&&endr<=1000){

        }else{
            System.out.println("Numbers is not divisible by 10");
        }
    }else{
        System.out.println("Numbers is not divisible by 10");
    }

輕松做:

Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
  System.out.println("Enter the Starting Number of the Range: ");
  startr = keyboard.nextInt();
  if(startr % 10 == 0 && startr >= 0)
    good = true;
  else
    System.out.println("Numbers is not divisible by 10");
}
while (!good);

good = false;
do
{
    System.out.println("Enter the Ending Number of the Range: ");
    endr = keyboard.nextInt();
    if(endr % 10 == 0 && endr <= 1000)
      good = true;
    else
      System.out.println("Numbers is not divisible by 10");
}
while (!good);

// do stuff

您需要使用一段時間,例如:

while conditionsMet is false
    // gather input and verify
    if user input valid then
        conditionsMet = true;
end loop

應該這樣做。

通用過程是:

  1. 無限循環讀取輸入。
  2. break; 滿足條件時退出循環的語句。

例:

Scanner keyboard = new Scanner(System.in);
int startr, endr;

for (;;) {
    System.out.println("Enter the starting number of the range: ");
    startr = keyboard.nextInt();
    if (startr >= 0 && startr % 10 == 0) break;
    System.out.println("Number must be >= 0 and divisible by 10.");
}

for (;;) {
    System.out.println("Enter the ending number of the range: ");
    endr = keyboard.nextInt();
    if (endr <= 1000 && endr % 10 == 0) break;
    System.out.println("Number must be <= 1000 and divisible by 10.");
}

如果在無效輸入后您只想顯示錯誤消息而不重復初始提示消息,請將初始提示消息移到循環的上方/外部。

如果您不需要單獨的錯誤消息,則可以重新安排代碼以使用do-while循環檢查條件,該條件稍短一些:

Scanner keyboard = new Scanner(System.in);
int startr, endr;

do {
    System.out.println("Enter the starting number of the range.");
    System.out.println("Number must be >= 0 and divisible by 10: ");
    startr = keyboard.nextInt();
} while (!(startr >= 0 && startr % 10 == 0));

do {
    System.out.println("Enter the ending number of the range.");
    System.out.println("Number must be <= 1000 and divisible by 10: ");
    endr = keyboard.nextInt();
} while (!(endr <= 1000 && endr % 10 == 0));

暫無
暫無

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

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