【问题标题】:Multiple and/or conditions in a java while loopjava while循环中的多个和/或条件
【发布时间】:2016-02-17 15:25:57
【问题描述】:

我希望当用户的输入是非整数值、小于1的整数值或大于3的整数值时执行while循环。一旦输入有效,我将使用它。但是,循环仅在用户输入非整数值时起作用。我已经把逻辑走完了,但我仍然不确定出了什么问题。

代码:

  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;

【问题讨论】:

  • 我认为您的问题是您同时使用 scnr.nextInt() 两次。如果我是你,我会使用: int myInput = scnr.nextInt(); while(myInput>3 || myInput

标签: java loops while-loop logic


【解决方案1】:

"while" 本身可以正常工作。在这种情况下不需要“做”。这是您的代码:

 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;

当你想至少执行一次代码然后检查“while”条件时,你需要“do”。

此外,每次调用 nextInt 实际上都需要输入中的 next int。所以,最好像这样只使用一次:

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

【讨论】:

    【解决方案2】:

    我对此并不完全确定,但一个问题可能是多次调用scnr.nextInt()(因此您可以将值赋给一个字段以避免这种情况)。 一个易于阅读的解决方案是引入一个测试器变量,正如@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();
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-14
      • 2013-08-07
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2015-09-29
      • 2016-03-30
      • 1970-01-01
      相关资源
      最近更新 更多