# Boolean always true?? What am I doing wrong?

• 03-02-2011, 06:46 PM
Forty0ztoFreedom
Boolean always true?? What am I doing wrong?
First let me say that I've found a way to achieve my goal not using a boolean anyway, but I still can't let go of this problem until I figure it out and it feels cheap if I just forget about it.

This program determines if a number is a prime number. After a loop which tests if the given number is divisible by 1 to 1 less than the given number (and is not 1 itself, and is not being divided by 1), it should switch the boolean value to false and break the loop. Otherwise, it keeps going until the loop breaks itself (the counter matches the number being tested) and the boolean value stays true.

This sounds great and logical to me, but the boolean is ALWAYS staying true! The program is saying every number you enter is a prime number! What am I doing wrong?

Code:
Code:

```//declare and construct variables                 int iNumber = 0, iPrimeCheck = 0;                 String sOutput = "", sNumber = "";                 boolean bIsPrime = true;         sNumber = JOptionPane.showInputDialog("Enter a number: ");                 iNumber = Integer.parseInt(sNumber);                 for (iPrimeCheck = 1; iPrimeCheck < iNumber; iPrimeCheck++)                 {                         if (iNumber % iPrimeCheck == 0 && (iNumber != 1 && iPrimeCheck != 1))                         {                                 bIsPrime = false;                             break;                     }                 }                 if (bIsPrime == true)                     sOutput = "Prime!";                 else                     sOutput = "Not Prime!";         //display message to user with sOutput                 JOptionPane.showMessageDialog(null,                                               sOutput,                                               "Prime Numbers",                                               JOptionPane.INFORMATION_MESSAGE);             System.exit(0); //exit```
• 03-02-2011, 07:02 PM
KevinWorkman
This seems to work okay for me. It just told me that 8 and 10 are not prime. What values are you using to generate incorrect output?
• 03-02-2011, 07:04 PM
sunde887
Try starting the loop at 2 and only test
Code:

`if(number % i == 0)`
The code however looks fine, although it can be made to look a bit better.
• 03-02-2011, 07:05 PM
Shoss
It also seemed to be working for me.
• 03-02-2011, 07:13 PM
Forty0ztoFreedom
What the . .

This thing is just frying my brain. For some reason I thought 3 was not a prime number and assumed I was getting bad results. Wow.

These little Math assignments are the hardest part of learning JAVA. You have to go back to stuff you haven't learned about in 10 years. Its like building a deck on mud.

Sorry!