Java:即使条件为false,Loop仍然在运行

时间:2017-03-02 04:41:07

标签: java loops while-loop java.util.scanner do-while

我在编码和java方面都相当新,但我希望我能解决这个问题。我有一个while循环和内部,如果在扫描仪中输入了错误的值,我有一个while语句。但是,当我运行代码时,它总是运行while命令一次,无论它是不正确还是正确,然后正确运行代码。

import java.util.Scanner;
public class Practice {
public static void main (String [] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";

Scanner user = new Scanner(System.in);


do
{
    System.out.println("Enter an integer between 1 and 15: ");
    x = user.nextInt();



        while ( x < 1 || x > 15);
        {
            System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
            x = user.nextInt();
        }

    n = 1;  


}
while (n != 1);


for (i = 1; i <= x; i++)
{
    S1 = S1 + "X";
}

for (n = 1; n <= x; n++)
{
    System.out.println(S1);
}


    }


}

提前非常感谢你。

3 个答案:

答案 0 :(得分:4)

从while循环中删除额外的;

像这样:

  while ( x < 1 || x > 15){
            System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
            x = user.nextInt();
}

答案 1 :(得分:2)

while(x <1 || x> 15); Semi-Colon将终止逻辑,控制将始终传递到下一行。编码时要小心:D

答案 2 :(得分:0)

  1. 删除额外的分号。
  2. 同时关闭扫描仪对象(用户)。
  3. 检查更新的代码。

    public class Practice {
        public static void main(String[] args) {
            int x = 0;
            int i = 0;
            int n = 0;
            String S1 = "";
    
            Scanner user = new Scanner(System.in);
            do {
                System.out.println("Enter an integer between 1 and 15: ");
                x = user.nextInt();
    
                while (x < 1 || x > 15)
                {
                    System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
                    x = user.nextInt();
                }
    
                n = 1;
    
            } while (n != 1);
    
            for (i = 1; i <= x; i++) {
                S1 = S1 + "X";
            }
    
            for (n = 1; n <= x; n++) {
                System.out.println(S1);
            }
    
            user.close();
    
        }
    
    }