Java 中嵌套循环的类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2793297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:51:40  来源:igfitidea点击:

Types of Nested Loops in Java

javafor-loop

提问by dominoos

I have a simple question. I have to find out many nested loops as possible in java. I have something like for loop and if statement inside. i know that we can do like if{if{if{if{something like that too. just need some more idea of more types of nested loops.

我有一个简单的问题。我必须在java中尽可能找出许多嵌套循环。我有类似 for 循环和 if 语句的东西。我知道我们也可以做类似的if{if{if{if{事情。只需要对更多类型的嵌套循环有更多的了解。

if you can write down some examples. I'll be very glad. thank you.

如果你能写一些例子。我会很高兴的。谢谢。

public class Test {
    public static void main (String []args) {
        int i = 0;

        for(int j = 1; j <= 5; j++) {
            if(j == 1 || j == 5) {
                i = 4;
            } else {
                i = 1;
            }
            for(int x = 0; x < i; x++) {
                System.out.print("**");
            }
            System.out.println();
         }
    }
}

回答by polygenelubricants

You can nest as many for/whileloops as you'd practically want in Java: there's no practical limit.

您可以在 Java 中嵌套任意数量的for/while循环:没有实际限制。

Java has 4 looping constructs:

Java 有 4 种循环结构:

Java does not have goto(which isn't really needed anyway).

Java 没有goto(无论如何都不需要)。

See also

也可以看看



Examples

例子

This is a typical example of a simple "triangle"-type nested loop, where the number of iteration of the inner loop depends on the value being iterated in the outer loop:

这是一个简单的“三角形”类型嵌套循环的典型示例,其中内循环的迭代次数取决于外循环中被迭代的值:

for (int i = 1; i <= 5; i++) {     // prints:
   for (int j = 0; j < i; j++) {   // *
      System.out.print("*");       // **
   }                               // ***
   System.out.println();           // ****
}                                  // *****

Here's an example of a "pairing"-type nested loop, where the two loops are independent of each other, using the for-each construct:

这是“配对”类型嵌套循环的示例,其中两个循环彼此独立,使用 for-each 构造:

int[] numbers = { 1, 2, 3 };                       // prints:  // if swapped:
char[] letters = { 'A', 'B', 'C' };                // 1 A      // 1 A
                                                   // 1 B      // 2 A
for (int number : numbers) {                       // 1 C      // 3 A
   for (char letter : letters) {                   // 2 A      // 1 B
       System.out.println(number + " " + letter);  // 2 B      // 2 B
   }                                               // 2 C      // 3 B
}                                                  // 3 A      // 1 C
                                                   // 3 B      // 2 C
                                                   // 3 C      // 3 C

The for-eachconstruct, which lacks explicit indices, makes the indepedence of both loops obvious: you can swap the two forstatements in the above code, and you'd still get all pairs, though listed in a different order.

for-each构造缺少显式索引,这使得两个循环的独立性显而易见:您可以交换for上述代码中的两个语句,并且您仍然会得到所有对,尽管以不同的顺序列出。

This use of a booleanmethod for a whileloop (this one from java.util.Scanner) is typical:

这种循环boolean方法的使用while(来自java.util.Scanner)是典型的:

Scanner sc = new Scanner("here we go again");     // prints:
while (sc.hasNext()) {                            // hereeeee
   String s = sc.next();                          // weeeee
   char lastChar = s.charAt(s.length() - 1);      // gooooo
   for (int i = 0; i < 4; i++) {                  // againnnnn
      s += lastChar;
   }
   System.out.println(s);
}

And here's an example that shows how do-whileis different from while-doand for:

这是一个示例,显示了do-whilewhile-do和 的不同之处for

    int x = 0;
    do {
        System.out.println("Hello!!!");
    } while (x != 0);

The above loop prints Hello!!!: the body of a do-whileis executed before the termination condition is checked.

上面的循环打印Hello!!!:在do-while检查终止条件之前执行a 的主体。



A more elaborate example

一个更详细的例子

Here's an example of a nested-loop logic, but refactored into methods to make things more readable. This is something that is important for beginners to learn: just because you can physically nest loops as many levels as you want, doesn't mean you should. By breaking apart the logic like this, the program becomes more modular and readable, and each logic stands on its own and can be tested and reused, etc.

这是一个嵌套循环逻辑的示例,但已重构为方法以使事情更具可读性。这一点对于初学者来说很重要:仅仅因为您可以根据需要在物理上嵌套多个级别的循环,并不意味着您应该。通过像这样分解逻辑,程序变得更加模块化和可读性更强,每个逻辑都独立存在,可以测试和重用等。

This snippet reverses the letters of a word in a char[]in-place.

此代码段char[]原位反转单词的字母。

static void swap(char[] arr, int i, int j) {
    char t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}
static void reverse(char[] arr, int from, int to) {
    int N = (to - from);
    for (int i = 0; i < N / 2; i++) {
        swap(arr, from+i, to-1-i);
    }
}
public static void main(String[] args) {
    char[] sentence = "reversing letters of words in sentence".toCharArray();
    final int L = sentence.length;
    int last = 0;
    for (int i = 0; i <= L; i++) {
        if ((i == L) || (sentence[i] == ' ')) {
            reverse(sentence, last, i);
            last = i + 1;
        }
    }
    System.out.println(new String(sentence));
    // prints "gnisrever srettel fo sdrow ni ecnetnes"
}

This example is also instructive in that even though it's essentially a nested loop algorithm, it's actuallyO(N)! It's a mistake to think that any doubly nested-loop algorithm must be O(N^2)-- it really depends on the algorithm itself more than just the physical structure.

这个例子也很有启发性,尽管它本质上是一个嵌套循环算法,但它实际上是O(N)! 认为任何双嵌套循环算法都必须如此是错误的O(N^2)——它实际上取决于算法本身,而不仅仅是物理结构。



Nested-loop Algorithms

嵌套循环算法

These are classical algorithms traditionally implemented using nested loops (at least in their naive forms):

这些是传统上使用嵌套循环实现的经典算法(至少以其幼稚的形式):

These are far from an exhaustive sampling, but it should provide a good introduction to a variety of nested forloops algorithms for beginners.

这些远非详尽的抽样,但它应该for为初学者提供对各种嵌套循环算法的很好的介绍。

回答by Mark Byers

The code if { if { if { ... } } }is not an example of nested loops. ifdoes not use loop.

该代码if { if { if { ... } } }不是嵌套循环的示例。if不使用循环。

Looping expressions are for example forand while.

循环表达式例如forwhile

回答by jweyrich

Loops can be done using the 3 basic loop statements: for, whileand do..while. However, if your question is about how many typesof nested loops are possible in Java, I'd say LOTS, since you can arrange and mix them as you wish.

可以使用 3 个基本循环语句来完成循环:forwhiledo..while。但是,如果您的问题是关于Java 中可能有多少种类型的嵌套循环,我会说LOTS,因为您可以根据需要安排和混合它们。

回答by Sean Owen

I like the previous answer, but in an attempt to answer directly this curious question:

我喜欢以前的答案,但为了直接回答这个奇怪的问题:

if-elseis not a loop type. Java has for, while, and do-whileloops. You could argue the the "foreach" syntax for forloops, introduced in Java 5, is a different kind of loop for your purpose. But really it is just shorthand for writing a while loop.

if-else不是循环类型。Java有forwhiledo-while循环。您可能会争辩说for,Java 5 中引入的循环的“foreach”语法是一种不同类型的循环。但实际上它只是编写 while 循环的简写。

But all of these "different" loop types are just language constructs. In the byte code that is compiled, they're not intrinsically different.

但是所有这些“不同”的循环类型都只是语言结构。在编译的字节码中,它们本质上没有区别。

回答by fredoverflow

I guess it depends on the compiler. I wrote a simple test program that generates Java files with different levels of loop nesting.

我想这取决于编译器。我编写了一个简单的测试程序,它生成具有不同级别循环嵌套的 Java 文件。

import java.io.BufferedWriter;
import java.io.FileWriter;

public class NestingTest
{
    public static void main(String[] args) throws Exception
    {
        for (int n = 1; n < 10000; ++n)
        {
            String className = "test" + n;
            FileWriter fw = new FileWriter("f:/test/" + className + ".java");
            BufferedWriter o = new BufferedWriter(fw);
            o.write("public class ");
            o.write(className);
            o.write("\n{\npublic static void main(String[] args) {\n");
            for (int i = 0; i < n; ++i)
            {
                o.write("while(true) {\n");
            }
            for (int i = 0; i < n; ++i)
            {
                o.write("}\n");
            }
            o.write("}\n}\n");
            o.close();
        }
    }
}

Once the files are generated, you do a manual binary search. Compile test5000. If it succeeds, compile test7500, and if it doesn't, compile test2500. After 13 or 14 steps, you should come to a conclusion.

生成文件后,您将进行手动二进制搜索。编译 test5000。如果成功,编译test7500,如果不成功,编译test2500。经过 13 或 14 个步骤后,您应该得出结论。

My compiler's sweetspot seems to be 5345 levels of nesting for this simple program, so I guess in practice it doesn't matter at all.

对于这个简单的程序,我的编译器的甜蜜点似乎是 5345 级嵌套,所以我想实际上这根本无关紧要。

回答by fastcodejava

Yeah, nesting has no limit.

是的,嵌套没有限制。