You declare `flag = true`

at the start of your program. Then, as soon as you find a factor, it gets set to `false`

, so you know the number is not prime.

But then, when another number is input by the user, `flag`

is **already false**. You need to set it to `true`

each time you get a new number from the user.

```
// no need to declare flag before the loop
for(;;) {
// initialise flag to true for each input number
boolean flag = true;
System.out.print("\nPlease enter a number : ");
n = in.nextInt();
...
```

```
if (flag) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
flag = true;
```

Hopefully that would help? Once the variable flag becomes false, your code allows no instruction to reset it back to default state for the next iterations inside for(;;) loop

Others have pointed out your error. I have a couple of other comments on your code.

First, your prime checking system works, but is inefficient. The Sieve of Eratosthenes is much faster than Trial Division, the method you are using. Even with just trial division your code can be made faster by using a limit of sqrt(n) in place of `n / 2`

and treating even numbers separately. It is also traditional to keep the main code cleaner by putting prime checking into a separate boolean method:

```
boolean isPrime(int num) {
// Low and negative numbers.
if (num < 2) {
return false;
}
// Even numbers.
if (num % 2 == 0) {
// Two is the only even prime.
return num == 2;
}
// Odd numbers.
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
} // end isPrime()
```

That method can be reused whenever you need to check for prime numbers.

Second, your handling of the loop in your main code seems clumsy, such as using a `break`

to exit. Given that you are repeatedly reading input from your user until a 0 is entered, then a `do ... while`

loop fits best:

```
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
do {
System.out.print("\nPlease enter a number or 0 to quit : ");
n = in.nextInt();
if (isPrime(n)) {
System.out.println(n + " is a prime number.");
} else {
System.out.println(n + " is not a prime number.");
}
} while (n != 0);
}
```

This uses the `isPrime()`

method from earlier, which replaces your `flag`

variable. Notice that using a `do ... while`

loop eliminates the explicit `break`

from the loop. That is because that style of loop is a better fit for what you are doing than the `for`

loop you used earlier. The `for`

loop would be better if you knew in advance how many numbers you were going to have to test.