简体   繁体   中英

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. I have a do while loop and inside that, I have a while statement if the incorrect value is input in the Scanner. 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.

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

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); The Semi-Colon will terminate the logic and the control will pass to the next line always. Be careful while you code :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();

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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