简体   繁体   English

Java:即使条件为false,While循环仍在运行

[英]Java: While Loop still running even when the condition is false

I'm fairly new at coding and in java in general but I'm hoping that I could get this figured out. 我在编码和Java方面还是一个新手,但我希望我能弄清楚这一点。 I have a do while loop and inside that, I have a while statement if the incorrect value is input in the Scanner. 我有一个do while循环,在里面,如果在Scanner中输入了错误的值,我有一个while语句。 However, when I run the code it always runs the while command once regardless of whether it is incorrect or correct and then runs the code correctly. 但是,当我运行代码时,无论是否正确或不正确,它总是运行一次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);
}


    }


}

Thank you so much in advance. 提前非常感谢您。

Remove the extra ; 删除多余的; from your while loop 从您的while循环

Like this: 像这样:

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

while ( x < 1 || x > 15); 而(x <1 || x> 15); The Semi-Colon will terminate the logic and the control will pass to the next line always. 分号将终止逻辑,并且控制将始终传递到下一行。 Be careful while you code :D 在编码时要小心:D

  1. Remove the extra semicolon in the while. 暂时删除多余的分号。
  2. Also close the scanner object(user). 同时关闭扫描仪对象(用户)。

Check the updated code. 检查更新的代码。

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();

    }

}

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

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