简体   繁体   English

一个素数程序,允许用户测试数字,直到用户输入零。 但是,在测试6个数字后,它会打印错误的消息

[英]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. 然而,在测试了大约6个数字之后,它打印出不正确的消息,就像它打印数字也是非素数的素数而且打印数字不是素数的素数。

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. 你在程序的开头声明了flag = true Then, as soon as you find a factor, it gets set to false , so you know the number is not prime. 然后,只要找到一个因子,就会将其设置为false ,因此您知道该数字不是素数。

But then, when another number is input by the user, flag is already false . 但是,当用户输入另一个数字时, flag 已经为假 You need to set it to true each time you get a new number from the user. 每次从用户处获取新号码时,都需要将其设置为true

// 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. Eratosthenes的筛子比试用师快得多,这是你正在使用的方法。 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. 即使只是通过试验分割,您可以通过使用sqrt(n)的限制代替n / 2并分别处理偶数来更快地编写代码。 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. 其次,你在主代码中处理循环看起来很笨拙,比如使用break来退出。 Given that you are repeatedly reading input from your user until a 0 is entered, then a do ... while loop fits best: 鉴于您反复阅读用户的输入,直到输入0为止,那么do ... while循环最适合:

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. 这使用了之前的isPrime()方法,它取代了你的flag变量。 Notice that using a do ... while loop eliminates the explicit break from the loop. 请注意,使用do ... while循环可以消除循环中的显式break That is because that style of loop is a better fit for what you are doing than the for loop you used earlier. 那是因为这种循环风格比你之前使用的for循环更适合你正在做的事情。 The for loop would be better if you knew in advance how many numbers you were going to have to test. 如果你事先知道要测试多少个数字, for循环会更好。

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 一旦变量标志变为false,您的代码就不允许指令将其重置回默认状态,以便(;;)循环内的下一次迭代

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

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