【问题标题】:Boolean logic for input validation输入验证的布尔逻辑
【发布时间】:2021-03-18 12:39:43
【问题描述】:

我有一种方法可以继续循环,直到用户输入设定范围内的数字。基本上它读取数组列表的大小,并验证用户输入是否大于-1,并且小于数组列表的大小。但是,我似乎无法正确使用布尔逻辑,它仍然接受错误的数字或者只有范围的一侧有效。这是代码

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
    
}

【问题讨论】:

  • 只要否定整个事情,应该没问题。 while ( !(choice &gt;= 0 &amp;&amp; choice &lt; mov.getArrayListSize()))
  • @Amongalen 刚刚尝试过但没有用。另一个其他建议
  • @JustAnotherDeveloper 仍然没有骰子......逻辑是有道理的,但现在它根本不接受任何数字?
  • Matthew 您是否尝试过Ambalens 版本或您编辑到问题中的版本?因为您的版本是“中间人”版本的错误“翻译”。
  • @Tom 我在编辑帖子之前先尝试了他的版本,然后我尝试了编辑中编写的版本。不幸的是,它们都不适合我

标签: java arraylist boolean boolean-logic boolean-expression


【解决方案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

没有可能既小于零又大于数组长度的选择解决方案。您几乎可以肯定要使用的是逻辑 OR,而不是 AND:

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

数轴上的解决方案是

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 2011-08-17
    • 1970-01-01
    相关资源
    最近更新 更多