Results 1 to 3 of 3
 11142013, 10:01 PM #1Member
 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; }
 11142013, 10:26 PM #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.If you don't understand my response, don't ignore it, ask a question.
 11142013, 11:50 PM #3Member
 Join Date
 Nov 2013
 Posts
 2
 Rep Power
 0
Similar Threads

Infinite loop
By F.S. in forum New To JavaReplies: 3Last Post: 03092012, 12:52 PM 
how to end infinite loop
By search4survival in forum New To JavaReplies: 14Last Post: 10252010, 08:59 AM 
boolean condition creating problem
By Basit781 in forum CLDC and MIDPReplies: 1Last Post: 05252010, 07:57 AM 
Infinite Loop
By bosoxfan in forum New To JavaReplies: 3Last Post: 02222010, 01:34 AM 
Infinite Loop
By rclausing in forum New To JavaReplies: 2Last Post: 01232010, 10:11 PM
Bookmarks