Reputation: 29
I am working on this program that is due shortly for class but cannot for the life of my figure out why I have an endless loop. This is my first coding class so this is all pretty new to me. I have figured out that the loop is coming from my "getLocation" method and I think something is wrong with the way I am trying to count my "location" variable, but like I said I am not sure. We have just started using multiple classes and private constructors and it is really throwing me off. I will take any help I can get. Thanks!
public int getLocation(){
while (location <= 250) {
location = 5;
location++; //endless loop here
System.out.println("test");
}
return location;
}
Upvotes: 0
Views: 59
Reputation: 35
You can NOT see if you are blind. I use lots of print statements so that I can see what the program is doing. If you do NOT know what the problem is, you do NOT know where to put the print statements. So put lots of print statements so you can see.
Upvotes: -1
Reputation: 2475
public int getLocation(){
while (location <= 250) {
location = 5; // every loop this equals 5
location++;
}
return location;
}
You set location equal to 5 every loop. Move this to before the while()
so that you only set it once then increment once per loop.
public int getLocation(){
location = 5; // this equals 5 initially
while (location <= 250) {
location++; // this will now increment appropriately
}
return location;
}
Upvotes: 2
Reputation: 140299
while (location <= 250) {
location = 5;
location++; //endless loop here
System.out.println("test");
}
location
can never exceed 250 in this loop. After executing the loop body, its value is always 6, because you set it to 5 and add 1.
So, provided location <= 250
when it reaches this loop, it will never stop.
Move the location = 5;
outside the loop body (or just delete it).
Upvotes: 3