有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个方法,它会继续循环,直到用户在设定的范围内输入一个数字。基本上,它读取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
    
}

共 (1) 个答案

  1. # 1 楼答案

    所以问题来了

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

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

    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范围内,这似乎是您需要的