用于输入验证的java布尔逻辑

6mzjoqzu  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(274)

我有一个方法,它会继续循环,直到用户在一个设定的范围内输入一个数字。基本上,它读取arraylist上的大小,并验证用户输入是否大于-1和小于arraylist大小。然而,我似乎不能得到布尔逻辑的权利,它仍然接受坏数字或只有一方的范围内工作。这是密码

public void Verify()
{

    do {
        System.out.printf("Enter the number\n");
        while (!input.hasNextInt()) 
        {
            System.out.printf("Enter the number\n");
                            input.next();
        }
        choice = input.nextInt();
    } while (choice < 0 && choice >  mov.getArrayListSize());//<--- this part

}
e37o9pze

e37o9pze1#

所以问题来了

while (choice < 0 && choice >  mov.getArrayListSize());

这意味着:保持循环,直到choice的值小于零,同时大于数组的大小。让我们看一些数字行:

xxxxxxxxxx
----------+---------+------------>   ... this shows a solution for choice < 0
          0         len

                     xxxxxxxxxxxx
----------+---------+------------>   ... this shows a solution for choice > len
          0         len

----------+---------+------------>   ... this shows a solution for the logical AND
          0         len

没有一种解决方案可以同时小于零和大于数组长度。你几乎可以肯定的意思是使用逻辑或,而不是和:

while (choice < 0 || choice >  mov.getArrayListSize());

数字行上的解决方案是

xxxxxxxxxx           xxxxxxxxxxxx
----------+---------+------------>   ... this shows a solution for choice > len
          0         len

循环将继续,直到值落在0-len范围内,这似乎是您需要的。

相关问题