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?
//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;
if (bIsPrime == true)
sOutput = "Prime!";
sOutput = "Not Prime!";
//display message to user with sOutput