-1

i just started with Java and wanted to write a code that tells me if something is a primenumber or not. But after i insert the number it gets stuck on the while function. What did I do wrong?

import javax.swing.JOptionPane;

public class Primenumber {

  public static void main(String[] args) {
    double number1, rest, x;
    boolean prime;

    number1 = Double.parseDouble(JOptionPane.showInputDialog("Insert a number: "));
    x = 2;
    rest = (number1 % x);

    while (rest != 0 | x == (0.5 * number1)) {
      x = x++;
      rest = (number1 % x);
    }
    if (rest == 0) {
      prime = false;
    } else {
      prime = true;
    }
    if (prime == true) {
      JOptionPane.showMessageDialog(null, number1 + " is a prime number ");
    } else {
      JOptionPane.showMessageDialog(null, number1 + " is not a prime number");
    }
  }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Anon Ymous
  • 167
  • 1
  • 2
  • 14

1 Answers1

1
while (rest != 0 || x <= (0.5 * number1)) {
    x++;
    rest = (number1 % x);
}

Two changes | is not what you want. || is what you are looking for (aka OR).

Also you don't want x == (0.5 * number1). This is the actual cause of your eternal while loop.

Finally change your double number1 to int number1, as an object it makes more sense.

Oh and like the comments mentioned x++; is what you want.

Edit: People commenting are correct | and || are both OR. However as this answer explains Difference between | and || in Java it's a matter of if you want to short circuit the OR or not.

Community
  • 1
  • 1
wiredniko
  • 2,491
  • 3
  • 19
  • 37
  • I'm not so good at Java, but using `|` for `boolean` seems valid. http://melpon.org/wandbox/permlink/d2GBlbdI4lrlGTw0 – MikeCAT Apr 14 '16 at 13:55
  • 1
    `|` vs `||` doesn't matter here really, neither operand has a side effect. – Andy Turner Apr 14 '16 at 13:55
  • `|` is technically also an `OR`, just that it does check the second condition aswell if the first one is true. – SomeJavaGuy Apr 14 '16 at 13:55
  • Note: changing `double number1` to `int number1` is good because this change to this code will also change types of `rest` and `x` to `int`. – MikeCAT Apr 14 '16 at 13:56
  • 1
    @Andy Turner ... it is just important that the second operand not have a side effect. The first operand will be evaluated in both the cases ;) – MS Srikkanth Apr 14 '16 at 13:58
  • When x == (0.5 * number1) is wrong, what should I use instead? Edit: nvm I saw your change. – Anon Ymous Apr 14 '16 at 14:01
  • `x <= ` will basically keep looking until x is no longer less then half of `number1` – wiredniko Apr 14 '16 at 14:26