Java 为什么变量的值会改变

Java 为什么变量的值会改变,java,Java,我不明白为什么在提供的代码中smallCountLoopCount的值从0变为1。我希望它保持在0。我使用IntelliJ IDEA进行测试。我有两条语句来审核这些值。它们分别是: System.out.println("SMALL LOOP COUNT = " + smallCountLoopCount); 第一个打印0,第二个打印1。要让第二个打印0,我需要更改什么 我试着用括号来确保数学正确,先做乘法,然后再做加法。看起来加法部分是在增加变量,而不是用它做数学运算 while (bigC

我不明白为什么在提供的代码中smallCountLoopCount的值从0变为1。我希望它保持在0。我使用IntelliJ IDEA进行测试。我有两条语句来审核这些值。它们分别是:

System.out.println("SMALL LOOP COUNT = " + smallCountLoopCount);
第一个打印0,第二个打印1。要让第二个打印0,我需要更改什么

我试着用括号来确保数学正确,先做乘法,然后再做加法。看起来加法部分是在增加变量,而不是用它做数学运算

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++;
}
实际结果:

SMALL LOOP COUNT = 0  
SMALL LOOP COUNT = 0
SMALL LOOP COUNT = 0  
SMALL LOOP COUNT = 1
这是因为您有smallCountLoopCount++;在循环体的末尾。显然,这两种回报都没有达到


如果更改为goal=0和bigCount=0,则您将获得所需的输出。

您的while循环底部有:

smallCountLoopCount++;
这不受任何条件的限制,因此将始终执行。如果没有完整的代码段,很难看出您到底在做什么,但是如果希望smallCountLoopCount保持为零,请删除上面的代码,如下所示:

                //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++ was here - Anything in this area will be executed regardless
                bigCountLoopCount++;
            }

这些值在哪里声明?你能在你的结果中澄清哪一个是零,哪一个是一吗?您正在声明smallCountLoopCount等于零,同时等于一。您是否尝试更改两个println语句以打印不同的文本,以确保它不是第一个执行两次的语句?smallCountLoopCount++;增加值。如果您认为不应该执行这一行,请调试您的应用程序。在smallCountLoopCount++行设置断点;看看原因。你知道这两行打印的代码来自同一行吗?