简体   繁体   English

嵌套 for 循环

[英]Nested for loops

I have a decent beginner understanding of regular for loops but I'm having trouble wrapping my head around nested for loops in Java.我对常规 for 循环有一个不错的初学者理解,但是我在 Java 中的嵌套 for 循环中遇到了麻烦。

In the problem I'm working on, I have a constant integer that is a max number, and then I ask the user for 4 different number inputs.在我正在处理的问题中,我有一个常量整数,它是一个最大数字,然后我要求用户输入 4 个不同的数字。 From those 4 inputs, I'm trying to determine which of them I can fit 'inside' the constant integer I declared.从这 4 个输入中,我试图确定哪些输入可以放入我声明的常量整数“内部”。

IE: If the constant integer is 30 and the user inputs 5, 9, 3, and 21 it will tell them they can only use the 5, 9, and 3 because the 21 would be too large to add. IE:如果常量整数是 30 并且用户输入 5、9、3 和 21,它会告诉他们他们只能使用 5、9 和 3,因为 21 太大而无法添加。

The problem in story form is, a user has a knapsack that holds a certain amount of weight.故事形式的问题是,用户有一个可以承受一定重量的背包。 The program asks the user to input 4 different item weights and then decides which items it can fit in the bag.该程序要求用户输入 4 个不同的物品重量,然后决定它可以放入包中的物品。

This is for a school project so I'm required to use nested for loops.这是一个学校项目,所以我需要使用嵌套的 for 循环。

Any easy way to think of nested for loops is to ignore the fact that they are nested.任何考虑嵌套 for 循环的简单方法是忽略它们嵌套的事实。 By convention, you will typically use i for the outer loop's increment counter and j for the inner loop's, which is the most important thing to keep straight in the beginning.按照惯例,您通常将i用于外循环的增量计数器,而j用于内循环,这是在开始时保持直线的最重要的事情。 If that is a point of confusion for you, it would likely benefit you to use more descriptive names for your increment variables than the letters 'i' and 'j', for example outer and inner .如果这对您来说是一个困惑点,那么为您的增量变量使用比字母 'i' 和 'j' 更具描述性的名称可能会有益于您,例如outerinner

At any given time when you are trying to structure your program's logic you only need to focus on the for loop that you are working most directly inside - at least when you are starting out and learning about them for the first time.在任何给定时间,当您尝试构建程序逻辑时,您只需要关注您最直接在内部工作的for循环 - 至少在您开始并第一次了解它们时。

I haven't done any JAVA but I know that C# is pretty much the same.我没有做过任何 JAVA,但我知道 C# 几乎是一样的。

I would do like this:我会这样做:

int max = 30;
int value = 0;
int counter = 0;
int[] input[4] = new int[5, 9, 3, 21];
bool[] canAddInput[4] = new bool[false, false, false, false];

for(value; value <= max; )
{
    for(counter; counter < 4; counter++)
    {
         value += input[i];
         if(value<=max)
             canAddInput[i] = true;
    }

    if(counter >= 4)
        Break;
}
package com.examplehub.basics;

public class ForNestedLoop {
    public static void main(String[] args) {

        /*
         * ####
         * ####
         * ####
         */
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 4; j++) {
                System.out.print("#");
            }
            System.out.println("\n");
        }

        /*
         * Outer loop iteration 1
         * i = 1; j = 1
         * i = 1; j = 2
         * i = 1; j = 3
         * i = 1; j = 4
         * Outer loop iteration 2
         * i = 2; j = 1
         * i = 2; j = 2
         * i = 2; j = 3
         * i = 2; j = 4
         * Outer loop iteration 3
         * i = 3; j = 1
         * i = 3; j = 2
         * i = 3; j = 3
         * i = 3; j = 4
         */
        for (int i = 1; i <= 3; ++i) {

            System.out.println("Outer loop iteration " + i);

            for (int j = 1; j <= 4; ++j) {
                System.out.println("i = " + i + "; j = " + j);
            }
        }

        /*
         * 1
         * 12
         * 123
         * 1234
         * 12345
         */
        for (int i = 1; i <= 5; ++i) {
            for (int j = 1; j <= i; j++) {
                System.out.print("" + j);
            }
            System.out.println();
        }

        /*
         * 1*1=1
         * 1*2=2    2*2=4
         * 1*3=3    2*3=6   3*3=9
         * 1*4=4    2*4=8   3*4=12  4*4=16
         * 1*5=5    2*5=10  3*5=15  4*5=20  5*5=25
         * 1*6=6    2*6=12  3*6=18  4*6=24  5*6=30  6*6=36
         * 1*7=7    2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49
         * 1*8=8    2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64
         * 1*9=9    2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81
         */
        for (int i = 1; i <= 9; ++i) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "*" + i + "=" + j * i + "\t");
            }
            System.out.println();
        }

        /*
         * A
         * AB
         * ABC
         * ABCD
         * ABCDE
         */
        for (int i = 1; i <= 5; i++) {
            char letter = 'A';
            for (int j = 1; j <= i; j++) {
                System.out.print(letter++);
            }
            System.out.println();
        }

        /*
         * 1 2 3
         * 4 5 6
         * 7 8 9
         */
        int[][] array = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }

        /*
         * 1 2 3
         * 4 5 6
         * 7 8 9
         */
        for (int[] ints : array) {
            for (int anInt : ints) {
                System.out.print(anInt + " ");
            }
            System.out.println();
        }
    }
}

source 来源

To understand nested loops, you can start with simple examples, and then try harder one.要理解嵌套循环,您可以从简单的示例开始,然后再尝试更难的示例。 For example, let's suppose you want to make a counter.例如,假设您想制作一个计数器。

int i, j;
for (i=0; i <= 9; i++)
{
    for (j=0; j <= 9; j++)
    {
        System.out.println(i+""+j)
    }
}

The output is numbers from 00 to 99. You can write the output of the loop in a paper or something to see how it works.输出是从 00 到 99 的数字。您可以将循环的输出写在纸上或其他东西上,看看它是如何工作的。 Let's take the example of this loop, you have this output:让我们以这个循环为例,你有这个输出:

00 //here your program entered the outer loop, i has now the value 0, after that, you enter to the inner loop, i remains 0, but j will change in the next iteration
01 // you are still in the first iteration of the outer loop, but the inner loop is on the second
02 // and so on ....
03
04
05
06
07
08
09 // ... until the inner loop finished looping
10 // once the inner loop finished looping, the outer loop changes again, and we are back to the inner loop

Once all that is clear on your mind, you can decide how your nested loop will be like.一旦您清楚所有这些,您就可以决定嵌套循环的样子。 What variables need to be used in the outer loop, and what variables for the inner loop.外循环需要使用哪些变量,内循环需要使用哪些变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM