# Infinite loop using boolean as condition

• 11-14-2013, 11:01 PM
midnightcoffee
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.

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;     }```
• 11-14-2013, 11:26 PM
Norm
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.
• 11-15-2013, 12:50 AM
midnightcoffee
Re: Infinite loop using boolean as condition
:(y): for you. Thanks.