嵌套 for 循环
我对常规 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
任何想到嵌套 for 循环的简单方法都是忽略它们是嵌套的这一事实。
按照惯例,您通常会使用
i
作为外部循环的增量计数器,使用j
作为内部循环的增量计数器,这是在开始时要保持直线的最重要的事情。如果这让您感到困惑,那么为增量变量使用比字母“i”和“j”更具描述性的名称可能会对您有利,例如outer
和inner
。在任何给定时间,当您尝试构建程序逻辑时,您只需要关注您最直接在内部工作的
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 andj
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 exampleouter
andinner
.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.我没有做过任何JAVA,但我知道C#几乎是一样的。
我会这样做:
I haven't done any JAVA but I know that C# is pretty much the same.
I would do like this:
要理解嵌套循环,您可以从简单的示例开始,然后再努力尝试。例如,假设您想制作一个计数器。
输出是从 00 到 99 的数字。您可以将循环的输出写在论文或其他东西中,看看它是如何工作的。
让我们以这个循环为例,您将得到以下输出:
一旦您清楚了所有内容,您就可以决定嵌套循环的样子。外循环需要使用哪些变量,内循环需要使用哪些变量。
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.
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:
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.
来源
source