# Prime Number Code Help!

Printable View

• February 6th, 2012, 05:47 PM
aandcmedia
Prime Number Code Help!
Alright, I am working with methods for the first time and need help, for some reason my program is not returning the right answer to tell if the number is prime or not, it is part of a larger code (thats why it starts out with an if statement)

Main:
Code :

``` if (inputi == 1){ //Grabs a number converts it than sends it to the method int exit = 0; do { String enter = JOptionPane.showInputDialog("Enter a number: "); int enteri = Integer.parseInt(enter); boolean kickback = isNotPrime(enteri);   if (kickback = true){ output = enteri + " is not a prime number!"; } else { output = enteri + " is a prime number!"; exit = 1; }   }while (exit > 1);```

isNotPrime Method:
Code :

```//Method for not prime numbers public static boolean isNotPrime(int number){ boolean prime = true; for (int i = 2; i < number; i++) { if (number % i == 0) { prime = false; break; }   } return prime; }```
• February 6th, 2012, 06:42 PM
Norm
Re: Prime Number Code Help!
Quote:

or some reason my program is not returning the right answer
Can you show the code's results for different inputs?
Are you sure you have a valid algorithm for the code?
If so, then try debugging it by adding printlns to see why the code is not doing what you want it to do.
Print out the values of the variables as the code executes.
• February 6th, 2012, 09:11 PM
Henry518
Re: Prime Number Code Help!
Well:

Code :

```if (number % i == 0) { prime = false; break; }```
If this condition is given, that means the number is NOT primer, because it has another dividend other than 1 or itself.
So by making prime = false given this condition, and then later you print it is a primer number, you have a mistake there.
• February 6th, 2012, 11:07 PM
chronoz13
Re: Prime Number Code Help!
look very carefull on your code, like what norm had said, are you sure you have the correct algorithm?

Prime number - Wikipedia, the free encyclopedia

your method only checks a divisibility, like if the number is even or odd