Thread: Infinite loop using boolean as condition

1. Member Join Date
Nov 2013
Posts
2
Rep Power
0 Infinite loop using boolean as condition

I'm getting what I believe is an infinite loop after inputting an integer >= 1. Why? Any help is appreciated.

Java Code:
public int calculateSequence(){
int n = 1;
int fnew = 1;
boolean calculateN = true;
boolean checkForValidInt = true;
while (checkForValidInt) {
System.out.print("Fibonacci Sequence - enter an integer to calculate: ");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()){
n = in.nextInt();
if (n < 1){
System.out.println("Error: must be greater than or equal to one");
}
else{
checkForValidInt = false;
}
}
else {
System.out.println("Error: must be an integer");
}
}
while (calculateN && n != 1 || n != 2 || n != 3) {
if (n != fnew){
n++;
fold1 = fold2;
fold2 = fnew;
fnew = fold1 + fold2;
}
else {
calculateN = false;
}
}
if (n == 1) {fnew = 1;} //sets value of fold1 to 1
if (n == 2) {fnew = 1;} //sets value of fold2 to 1
if (n == 3) {fnew = 2;} //sets value of fold 3 to 2

return fold1 + fold2;
}  Reply With Quote

2. Re: Infinite loop using boolean as condition

The condition n != 1 is true for all the other billion values of n that are not 1.
Using OR operators means that if any one of the conditions is true, the full expression is true.

Using an AND operator means that ALL of the conditions must be true for the full expression to be true.

Putting all sub conditions in ()s is safer code.  Reply With Quote

3. Member Join Date
Nov 2013
Posts
2
Rep Power
0 Re: Infinite loop using boolean as condition for you. Thanks.  Reply With Quote Posting Permissions

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