简体   繁体   中英

Java: Prime Number Program Not Working

Why does the int j only get the value 2? Doesn't (int)realNum mean that it must be a natural number?

Scanner basicNum = new Scanner(System. in );
String insertNum = JOptionPane.showInputDialog(null, "Insert a number\n");

int realNum = Integer.parseInt(insertNum);
int j = realNum = 1;

if (realNum < 10000) {
    while ((realNum / j == (int) realNum)) {
        j++;
    }
    System.out.println(j);
    if (j > 2) {
        JOptionPane.showMessageDialog(null, "It is not a prime!!");
    }

    if (j < 2) {
        JOptionPane.showMessageDialog(null, "It is a prime!");
    }
} else {
    JOptionPane.showMessageDialog(null, "Too large number!");
}

int j = realNum = 1; sets j and realNum to 1.

So realNum / j == (int)realNum is true until j is greater than 1. Hence your output.

The (int) prefix on (int)realNum is superfluous since realNum is already an int type.

Also realNum / j will be evaluated in integer arithmetic: any remainder is truncated.

In Java 8, you can easily do it like this:

boolean isPrime(final int n) {
    return IntStream.range(2, n / 2+1).noneMatch(i -> n % i == 0);
}

On earlier versions, this one should do the same work,

    String insertNum = JOptionPane.showInputDialog(null, "Insert a number\n");
    int realNum = Integer.parseInt(insertNum);
    boolean prime = true;
    for (int i = 2; i <= realNum / 2; i++) {
         if (realNum % i == 0) {
              JOptionPane.showMessageDialog(null, "It is not a prime!!");
              prime = false;
              break;
         }
    }
    if (prime) {
         JOptionPane.showMessageDialog(null, "It is a prime!");
    }

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