簡體   English   中英

是否可以在 Java 的 while 循環中分配變量

[英]Is it possible to assign a variable inside a while loop in Java

這可能是不好的做法,但我試圖從具有以下條件的用戶那里獲取輸入:lowerBound 必須小於 upperBound 也不能為零

如果不滿足這些條件中的任何一個,我想讓他們為變量輸入新值

int lowerBound;
    int upperBound;
    Scanner input = new Scanner(System.in);
    boolean loop = true;
    while(loop = true)
    {
        System.out.println("Enter a lower bound:");
        lowerBound = input.nextInt();
        System.out.println("Enter an upper bound:");
        upperBound = input.nextInt();
        if(lowerBound > upperBound || lowerBound <= 0 || upperBound <= 0)
        {
            System.out.println("Error lowerBound must be less than or equal to upperBound");
            System.out.println("Neither may be equal to zero, Try again");
        }
        else
        {
            loop = false;
        }
    }
    
    input.close();

您所擁有的將起作用,因為每次 if 條件失敗時,while 循環都會強制重復。 每次重復都會讓用戶在沒有丟失輸入的情況下登陸輸入。 所以簡短的回答是,您可以在 while 循環中更改變量。 這就是我們如何有效地打破循環。

這是一個無限循環,因為您在 while 內放置了一個賦值,無論它是否設置為 false,都使循環始終為真。

對於這種情況,可以這樣簡化:

int lowerBound;
int upperBound;
Scanner input = new Scanner(System.in);
while(true)
{
    System.out.println("Enter a lower bound:");
    lowerBound = input.nextInt();
    System.out.println("Enter an upper bound:");
    upperBound = input.nextInt();
    if(lowerBound > upperBound || lowerBound <= 0 || upperBound <= 0)
    {
        System.out.println("Error lowerBound must be less than or equal to upperBound");
        System.out.println("Neither may be equal to zero, Try again");
    }
    else
    {
        break;
    }
}

input.close();

暫無
暫無

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

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