I have written a program to figure out hotel occupancy. I completed the program, but my results keep coming out as an infinite loop and I have no idea why! I know it has to be false to stop the loop and I thought I had it right. I don't know if it's a stupid mistake I have done or if there is something missing. This didnt' work, but I tried putting a break statement at the end of the final 'System.out.println' section, but that brought up the number of floors again after showing me all the information. The break statement may be totally wrong there, but I am just going by what I know so far! The program must be written with while loops.
Thanks for you help, this forum has been a huge help
I think you need to take a step back from the code, and work it out on paper.
Specifically look at what your loop conditions should be. When are you free to go to the next "part" of your program.
For instance the first case is "while (floors < 1) - Loop until the user enters a valid number for "floors".
Your second loop: while (floors > 1). Will this ever evaluate to true? What are you trying to achieve here?
Steps to avoid an infinite while loop
#1: Set it up for the first iteration (initialise)
#2: Within the loop, change something so that the loop condition won't evaluate with the same inputs, and you move 'closer' to your goal. This is often done by incrementing/decrementing a loop counter of some sort.
In your first loop, you change the test by getting the user to enter in another value for "floors"
What should you be changing in your second loop?
There are two endless loops in this code.
Carey pointed out the loop based on number < floors where neither number nor floors was changing in the loop, and so wouldn't end.
Jane Brown wrote:
Okay, I see what you are saying. So what do I do to print those statements once I have the number of rooms for each floor?
I've been working on this for a while now and can't get it right X.X
A loop does something repeatedly until a condition is matched as true.
A few variances for a simple loop are:
Of course, there are many more possibilities that we can do here, but for simplicity, I have just mentioned a few situations relative to your case.