0

I'm having some trouble figuring this out. I have a while statement with an expression that should be evaluated on each loop. I feel like I am thinking about this wrong.

What I'm trying to do is loop through the expression experience >= experienceCap until it is false. The experienceCap is set correctly on each loop, but the while expression values never change even though the values actually do change on each loop.

public void refreshExperience() {
    int experience = getExperience(); //10
    int experienceCap = getExperienceCap(); //100

    while (experience >= experienceCap) {
            newExperienceCap();
            refreshExperience();
    }

}

This results in some log output like:

experience: 10
experienceCap: 100
experience: 10
experienceCap: 450
experience: 10
experienceCap: 1120
experience: 10
experienceCap: 2337

And an inevitable crash. I would very much appreciate any input, thank you!

2
  • 1
    you need to update the int values in the loop, possibly just return experienceCap when you call newExperienceCap() Commented Apr 5, 2016 at 0:25
  • Can you please post the code for newExperienceCap() Commented Apr 5, 2016 at 0:35

2 Answers 2

1

The loop values are not being updated, so it is confusing that in your output it shows experienceCap increases. Without seeing all the code i can only guess that the values you are logging are not the ones declared in refreshExperiece.

public class Test {

    int experience = 10;
    int experienceCap = 100;

    public void refreshExperience() {
        while (experience <= experienceCap) {
            experience = getExperience();
            experienceCap = getExperienceCap();
        }
    }

The above code shows experience and experienceCap being initialized to 10 and 100 respectively. Inside the loop these values are updated with the returned value from getExperience and getExperienceCap respectively. How you are updating experience and experienceCap is up to you but this is a simple example:

private int getExperience() {
    return experience + 5;
}

private int getExperienceCap() {
    return experienceCap - 10;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, so that just sets experienceCap to 100 always, right? To answer your question, in my posted code newExperienceCap() sets a new cap, which is why you see the debug output with a new value. So it sets a new value each loop, but the loop while statement expression is not updated to that new value, and just stays at the first one: 10 thanks
1

This is a typical value vs reference problem. You seem to expect that int experience is a reference, but it is not.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.