繁体   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