Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

edumorlom
edumorlom
4,073 Points

Why doesn't the following for-loop running?

The following for-loop is being completely skipped. Can someone please help me out?

void moveAllCarsUp(int index){
        for (int i=index; i>0; i--){
            garage[i] = null;
        }
        garage[0] = null;
    }

2 Answers

I'm assuming that within your car class you have an attribute named numberMoved? Again I don't see anything wrong with the code you've posted here, except for maybe a misuse of a name in the method setNumberMoved, a more suitable name would be incrementNumberMoved. And maybe to make it clear that numberMoved is not a static attribute you could write this.numberMoved++ instead.

If you're still stuck with this problem, post the complete code. Or try debugging yourself using a debugger, set a breakpoint somewhere useful within your code and you'll see what's wrong more easily when you run the code in debug mode.

edumorlom
edumorlom
4,073 Points

Thank you! I did something different so that it would work but I don't understand why my previous code wasn't working. Anyways, it works now haha I'm studying Computer Science and this was a project so consider it project finished :)

There's nothing wrong with the code you've posted here, it correctly sets all values of the array with an index lower than the one passed to the method to null. So your problem is elsewhere. Can you post the entire code if this is possible?

edumorlom
edumorlom
4,073 Points

I'm actually having a different issue now. Why isn't this working? It's supposed to add 1 to every carObject after the index. The for-loop runs but for some reason the setNumberMoved() method does not add one.

    void allCarsAfterPlusOne(int index) {
        for (int i = index + 1; i < garage.length; i++) {
            if (garage[i] != null) {
                garage[i].setNumberMoved();
            }
        }
    }
    public void setNumberMoved() {
        numberMoved++;
    }