javawhile-loop

Why A Variable's Value Changes


I have researched an on-line course that I have taken, extensively, and have not found an answer. Here is my quandry: I do not understand why the value of smallCountLoopCount changes from 0 to 1 in the code provided. I expect it to remain at 0. I use IntelliJ IDEA for testing. I have two statements to audit the values. Each are:

System.out.println("SMALL LOOP COUNT = " + smallCountLoopCount);

The first prints 0 and the second prints 1. What do I need to change to have the second one print 0?

I've tried working the () brackets to try and ensure that the math flows correctly, doing the multiplication first and then the addition second. It looks like the addition piece is incrementing the variable instead of doing math with it??

while (bigCountLoopCount <= bigCount) {
    //System.out.println(bigCountLoopCount + " " + smallCountLoopCount);
    if ((bigCountLoopCount * 5) == goal) {
        //System.out.println("THIS TRUE ACTIVATED");
        return true;
    }
    System.out.println("SMALL LOOP COUNT = " + smallCountLoopCount);
    if (((bigCountLoopCount * 5) + smallCountLoopCount) == goal)
    {
        System.out.println("SMALL LOOP COUNT = " + smallCountLoopCount);
        System.out.println("THIS TRUE ACTIVATED by:");
        System.out.println(bigCountLoopCount + " " + smallCountLoopCount + " " + goal);
        return true;
    }
    smallCountLoopCount++;
    bigCountLoopCount++;
}

Expected result:

SMALL LOOP COUNT = 0  
SMALL LOOP COUNT = 0

Actual result:

SMALL LOOP COUNT = 0  
SMALL LOOP COUNT = 1

Solution

  • This is because you have smallCountLoopCount++; at the end of the loop body. And apparently it doesn't hit neither of the returns.

    If you change to goal=0 and bigCount=0 then you will get your desired output.