【问题标题】:How to use a nested loop to count up then down?如何使用嵌套循环向上计数然后向下计数?
【发布时间】:2018-12-19 17:32:07
【问题描述】:

我不知道如何使用嵌套循环向上计数然后向下计数。目前,我的输出是:

2
33
444
5555
66666

当我希望它像这样输出时:

2
33
444
33
2

我不确定如何解决这个问题。我一直在研究这个问题,但似乎不知道如何改变它来使其工作。

这是我当前产生第一个输出的代码:

【问题讨论】:

    标签: java loops nested-loops


    【解决方案1】:

    这个输出有两个有趣的属性。对于每一行i,我们可以这样说:

    1. 每行的字符数是itimes - i 之间的最小值。
    2. 要打印的字符是该行中的字符数 + 1。

    如果你把所有这些放在一起:

    int lines = 3;
    int times = lines * 2;
    String output = "";
    for(int i = 1; i < times; i++)
    {
        int numChar = Math.min(i, times - i);
        int toPrint = numChar + 1;
        for(int k = 1; k < toPrint; k++) {
            output += toPrint;
        }
    
        output += "\n";
    }
    System.out.println(output);
    

    【讨论】:

    • 所以我明白这一点。但是对于另一个输出,比如我有行 = 5,我希望它从 8 开始,然后倒计时,意思是这样的:(检查上面的编辑)
    【解决方案2】:

    在您的示例中,您的第二个内部循环什么都不做,它永远不会启动,只有第一个产生输出。我认为你的想法接近有四个循环,两个两个嵌套。这可行,但您只需要巧妙地使用两个嵌套循环。

    public static void main(String[] args){
        int lines = 3;
        int times = lines * 2;
        int x = 2;
        String output = "";
        for(int i = 1; i < times; i++) {
            for (int k = 1; k <= Math.min(times-i, i); k++) {
                output = output + x;
            }
    
            //Update the index
            if (i < times/2) {
                x++;
            } else  {
                x--;
            }
    
            output += "\n";
        }
        System.out.println(output);
    }
    

    诀窍在于如何使用第二个循环的索引:Math.min(times-i, i)

    编辑: 编辑后,您似乎希望数字“旋转”(即 ...8,9,0,1...)。为了实现这一点,您可以在内部循环中执行:

                String xS = String.valueOf(x);
                output += xS.charAt(xS.length()-1);
    

    另一个选项(在内循环之外):

            //Update the index
            if (i <= (times/2) - 1) {
                x++;
            } else  {
                x--;
            }
            x = x%10; //the rest of dividing x by 10
            output += "\n";
        }
    

    【讨论】:

    • 我看到了。这也有效,但我怎样才能让它重置为 0 并计数到 2 然后回退,因为目前当 x 从 8 开始并向上计数时,它会变为 10 12 等。
    • 我明白了。这行得通,但是一旦它达到“22222”,它就会继续回到 3333、444 等,当我需要它时,一旦它达到中间值倒计时。 (在原始帖子中检查上面的输出代码)
    • @JohnathanMinucco 更新了答案以符合要求
    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 2020-07-31
    • 2015-01-22
    • 2021-10-19
    • 2020-10-30
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    相关资源
    最近更新 更多