嵌套 for 循环

发布于 2024-12-11 21:24:09 字数 327 浏览 0 评论 0原文

我对常规 for 循环有很好的初学者理解,但我在理解 Java 中的嵌套 for 循环方面遇到了困难。

在我正在解决的问题中,我有一个最大数字常量整数,然后我要求用户输入 4 个不同的数字。从这 4 个输入中,我试图确定其中哪些可以适合我声明的常量整数“内部”。

IE:如果常量整数是 30,并且用户输入 5、9、3 和 21,它会告诉他们只能使用 5、9 和 3,因为 21 太大而无法相加。

故事形式的问题是,用户有一个可容纳一定重量的背包。该程序要求用户输入 4 种不同物品的重量,然后决定哪些物品可以放入袋子中。

这是一个学校项目,所以我需要使用嵌套 for 循环。

I have a decent beginner understanding of regular for loops but I'm having trouble wrapping my head around nested for loops in Java.

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. From those 4 inputs, I'm trying to determine which of them I can fit 'inside' the constant integer I declared.

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.

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.

This is for a school project so I'm required to use nested for loops.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暮光沉寂 2024-12-18 21:24:09

任何想到嵌套 for 循环的简单方法都是忽略它们是嵌套的这一事实。
按照惯例,您通常会使用 i 作为外部循环的增量计数器,使用 j 作为内部循环的增量计数器,这是在开始时要保持直线的最重要的事情。如果这让您感到困惑,那么为增量变量使用比字母“i”和“j”更具描述性的名称可能会对您有利,例如 outerinner

在任何给定时间,当您尝试构建程序逻辑时,您只需要关注您最直接在内部工作的 for 循环 - 至少当您开始学习它们时第一次。

Any easy way to think of nested for loops is to ignore the fact that they are nested.
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. 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.

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.

久夏青 2024-12-18 21:24:09

我没有做过任何JAVA,但我知道C#几乎是一样的。

我会这样做:

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;
}

I haven't done any JAVA but I know that C# is pretty much the same.

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;
}
瀟灑尐姊 2024-12-18 21:24:09

要理解嵌套循环,您可以从简单的示例开始,然后再努力尝试。例如,假设您想制作一个计数器。

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

输出是从 00 到 99 的数字。您可以将循环的输出写在论文或其他东西中,看看它是如何工作的。
让我们以这个循环为例,您将得到以下输出:

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

一旦您清楚了所有内容,您就可以决定嵌套循环的样子。外循环需要使用哪些变量,内循环需要使用哪些变量。

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.
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.

仅一夜美梦 2024-12-18 21:24:09
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();
        }
    }
}

来源

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文