【问题标题】:Reusing scanner input for multiple conditions in while loop在while循环中为多个条件重用扫描器输入
【发布时间】:2014-10-18 13:10:47
【问题描述】:

我想在while循环中使用单个扫描仪输入作为多个条件,可以检查输入是否正确,如果不正确则重新输入输入值。

类似这样的:

while(scannerInput is a int AND scannerInput is > than 0 AND scannerInput is < 10)
{
    //CODE
}

但如果我使用scanner.hasNextInt() 和scanner.nextInt() 它会提示我输入而不是使用相同的输入

while (scaner.hasNextInt() && scaner.nextInt() > 0 && scaner.nextInt() < 10)  {

}

有没有办法存储第一个输入并一次又一次地重复使用它,或者我的问题有更好的解决方案吗?

【问题讨论】:

标签: java


【解决方案1】:

scanner.nextInt() 的调用使扫描器读取其输入的位置前进,因此第二次读取可能会产生不同的数字,或者当只有一个 int 可用时抛出异常。要解决这种情况,您可以引入一个变量来保存第二次检查的值:

int tmp;
while (scaner.hasNextInt() && (tmp = scaner.nextInt()) > 0 && tmp < 10)  {
    ...
}

第二个子表达式(tmp = scaner.nextInt())scanner 中读取下一个整数值,并将其存储在临时变量tmp 中。之后,该值与 0 进行比较,最后将相同的值与 10 进行比较。

赋值是在检查tmp &lt; 10之前执行的,因为&amp;&amp;表达式的一部分是按照从左到右的顺序处理的。

这个解决方案并不理想,因为tmp 在循环之后仍然可见,而且它不是那么容易阅读。您最好将检查移动到循环内,如下所示:

while (scaner.hasNextInt()) {
    int val = scaner.nextInt();
    if (val < 0 || val >= 10) {
        break;
    }
    ...
}

我的想法是不断提示您输入新输入的代码,直到正确为止

实现此目的的常用方法是使用do/while 循环:

int val = -1;
do {
    System.out.print("Enter an int: ");
    if (scanner.hasNextInt()) {
        val = scanner.nextInt();
    } else {
        scanner.nextLine();
    }
} while (val < 0 || val >= 10);

【讨论】:

  • 是的,但在这种情况下,我不会被直接提示输入新的输入,我将不得不导航回这个方法,我的想法是代码不断提示您输入新的输入,直到它正确
【解决方案2】:

试试这个代码:

int s;
while (scanner.hasNext() && (s = scanner.nextInt()) >0 && s <0){
 #code          
}

【讨论】:

    【解决方案3】:

    这里有一些选择。

    1. 您可以在 while 中放置一个 if 条件,并给 while 一个 true 作为条件。让 if 语句打破 while 循环
    2. 您可以编写一个方法来进行检查并将scanner.nextInt() 作为参数提供

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2019-11-28
      • 2023-01-08
      相关资源
      最近更新 更多