简体   繁体   中英

a prime number program that allows the user to test numbers till the user enters zero. However, after testing 6 numbers, it prints incorrect message

a prime number program that allows the user to test whether a number is prime or not till the user enters zero. However, after testing about 6 numbers, it prints incorrect message like it prints the number is a prime for a non-prime number also and prints a number is not a prime number for prime numbers.

package com.selfexercise.exercise;

/**
* Created by One on 2/15/2017.
*/ 
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
    int n;
    boolean flag=true;

    Scanner in = new Scanner(System.in);
    for(;;) {
        System.out.print("\nPlease enter a number : ");
        n = in.nextInt();

        for (int i = 2; i <= n / 2; i++) {
            if (n % i == 0) {
                flag = false;
                break;
            }
        }
        if (flag) {
            System.out.println(n + " is a prime number");
        } else {
            System.out.println(n + " is not a prime number");
        }
        if(n==0)
            break;
    }
}
}

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

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.

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

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