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

1. Member
Join Date
Mar 2011
Posts
3
Rep Power
0

## 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:
Java 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```

2. 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?

3. Try starting the loop at 2 and only test
Java Code:
`if(number % i == 0)`
The code however looks fine, although it can be made to look a bit better.
Last edited by sunde887; 03-02-2011 at 07:07 PM.

4. It also seemed to be working for me.

5. Member
Join Date
Mar 2011
Posts
3
Rep Power
0
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!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•