【问题标题】:Nested While Loop Logical Error嵌套 While 循环逻辑错误
【发布时间】:2014-02-13 05:03:52
【问题描述】:

我是 Java 新手,我正在尝试理解嵌套的 while 循环。我正在尝试编写一个程序来打印以下输出:

999999999 on the top line,
88888888 on the next,
7777777 etc,
666666 etc,
55555
4444
333
22
1

我很容易使用 for 循环来做到这一点,但现在我想用 While 循环来做同样的事情。问题是我的代码在当前状态下只打印第一行九,然后看起来内部的 While 循环不再运行了。

我非常困惑,我认为我的任何标准都不是重言式,但我不太了解重言式。请解释我的循环逻辑有什么问题。循环对我来说仍然是一种神秘的巫术。

int outer = 9;
int inner = 1;

while (outer >= 1)
    {   
        while(inner <= outer)
            {
                System.out.print(outer);
                inner++;
            }
        System.out.println();
        outer--;
    }

【问题讨论】:

    标签: java while-loop nested-loops


    【解决方案1】:

    您必须在第二个 while 循环之后重置 inner 的值。

    while (outer >= 1){   
            while(inner <= outer){
                    System.out.print(outer);
                    inner++;
            }
            inner = 1;
            System.out.println();
            outer--;
     }
    

    另请注意,快速使用调试器,或者简单地用笔和纸查看每次迭代中每个变量的值是什么,比在这里提问更快。

    【讨论】:

    • 我一发布就意识到这一点,哈哈。感谢您的帮助!我觉得自己像个菜鸟。
    • @user2993456 我通常发现(在学习时)通过在循环的每个状态下写下变量值来在纸上空运行代码很有帮助。
    • 感谢您的建议。这次我超前了,但我以后一定会试试你的方法!
    【解决方案2】:

    每次都需要重置inner

    while (outer >= 1) {   
        inner = 1; // ADD THIS LINE
        while(inner <= outer)
            {
                System.out.print(outer);
                inner++;
            }
        System.out.println();
        outer--;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多