简体   繁体   English

Java While循环中的多个和/或条件

[英]Multiple and/or conditions in a java while loop

I want the while loop to execute when the user's input is a non-integer value, an integer value less than 1, or an integer value greater than 3. Once the input is valid, I will use it. 我希望当用户输入的值是非整数值,小于1的整数值或大于3的整数值时执行while循环。输入有效后,我将使用它。 However, the loop only works when the user inputs a non-integer value. 但是,该循环仅在用户输入非整数值时有效。 I have gone through the logic and I am still not sure what's wrong. 我已经了解了逻辑,但仍然不确定出什么问题。

Code: 码:

  Scanner scnr = new Scanner(System.in);
  do {

     System.out.println("Please enter an integer value 1-3 for the row.");

     while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
     {

        System.out.println("Your input is not valid.");
        System.out.println("Please enter an integer value 1-3 for the row.");
        scnr.next();
     }
     row = scnr.nextInt() - 1;

"while" works fine by itself. “ while”本身可以正常工作。 No "do" is required in this case. 在这种情况下,不需要“执行”。 Here is your code: 这是您的代码:

 Scanner scnr = new Scanner(System.in);

 System.out.println("Please enter an integer value 1-3 for the row.");

     while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
     {
        System.out.println("Your input is not valid.");
        System.out.println("Please enter an integer value 1-3 for the row.");
        scnr.next();
     }
     int row = scnr.nextInt() - 1;

You need "do" when you want to execute code at least once and then check "while" condition. 当您想至少执行一次代码然后检查“ while”条件时,需要“ do”。

Also each call for nextInt actually requires next int in the input. 同样,对nextInt的每次调用实际上都需要输入中的next int。 So, better use it only once like this: 因此,最好只使用一次,如下所示:

int i;
while((i=scnr.hasNextInt() && (i > 3)) || (scnr.hasNextInt() && (i < 1)) || (!scnr.hasNextInt()))

I am not completly sure about this, but an issue might be calling scnr.nextInt() several times (hence you might give the value to a field to avoid this). 我对此并不完全确定,但是问题可能是多次调用scnr.nextInt() (因此,您可以将值赋予字段以避免这种情况)。 An easy to read solution would be introducing a tester-variable as @Vikrant mentioned in his comment, as example: 一个易于阅读的解决方案是引入一个测试变量,例如@Vikrant在他的评论中提到的,例如:

 System.out.println("Please enter an integer value 1-3 for the row.");
 boolean invalid=true;
 int input=-1;

 while(invalid)
 {
    invalid=false;
    if(scnr.hasNextInt())
         input=scnr.nextInt();
    else
         invalid=true;
    if(input>3||input<1)
         invalid=true;
    if(!invalid)
        break;
    System.out.println("Your input is not valid.");
    System.out.println("Please enter an integer value 1-3 for the row.");
    scnr.next();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM