Java中嵌套循环的类型 [英] Types of Nested Loops in Java

查看:109
本文介绍了Java中嵌套循环的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题。我必须在java中找出许多嵌套的循环。我有东西像循环和if语句里面。我知道我们可以像那样做,如果{if {if {if {if {>也是这样的。只需要更多的更多类型的嵌套循环的想法。

如果你可以写下一些例子。我会很高兴。感谢您。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ int i = 0; (j = 1; j <= 5; j ++){
if(j == 1 || j == 5){
i = 4;
} else {
i = 1;

for(int x = 0; x System.out.print(**);
}
System.out.println();




$ div class =h2_lin>解决方案

/ 循环可以像Java中实际需要的一样嵌套:实际的限制。

Java有4个循环结构:
$ b $ ul

  • JLS 14.14 代表声明


  • JLS 14.12 while 语句

  • JLS 14.13 do Statement (又名 do-while



  • Java没有 goto (这不是真的需要)

    参见








    示例



    这是一个典型的简单的三角型嵌套循环,其中内部循环的迭代次数取决于在外部循环中迭代的值:

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

    下面是一个例子一个配对类型的嵌套循环,其中两个循环是相互独立的,使用for-each构造:

    pre $ code > int [] numbers = {1,2,3}; //打印://如果交换:
    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

    for-each construct,它缺少显式的索引,使得两个循环的独立性显而易见:你可以在上面的代码中交换两个 for 语句,你仍然可以得到所有的对,尽管以不同的顺序列出。

    对<$ c $使用布尔值 c> while loop(来自

     <$ c    $ c>扫描仪sc =新扫描仪(我们再去); // print:
    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);



    $ b $ p
    $ b

    下面是一个例子,显示 do-while 不同于 while-do

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

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




    一个更详细的例子



    下面是一个嵌套循环逻辑的例子,但重构成方法使事情更具可读性。这对于初学者来说是非常重要的:仅仅因为你可以根据自己的想法在不同层次上嵌套循环,并不意味着你应该。通过分解这样的逻辑,程序变得更加模块化和可读,每个逻辑独立,可以被测试和重用等等。在$ char [] in-place中的一个单词的字母。

    pre $ 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);
    (int i = 0; i swap(arr,from + i,to-1-i)


    public static void main(String [] args){
    char [] sentence =在句子中反转字母.toCharArray();
    final int L = sentence.length;
    int last = 0;
    for(int i = 0; i <= L; i ++){
    if((i == L)||(sentence [i] =='')){
    (句子,最后,我);
    last = i + 1;
    }
    }
    System.out.println(new String(sentence));
    //打印



    $ p



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




    嵌套循环算法



    这些是传统的算法使用嵌套循环(至少在他们的天真形式):

    $ ul $ b $ li $ $ c $ O> O(N ^ 2)排序算法:


    • Bubble sort

    • 选择排序

    • 插入排序


    • $ li $ code> O(N ^ 3)三重嵌套循环算法:


      • 矩阵乘法


      • $ b
      • 表填充动态编程算法



        这些都不是一个详尽的示例,但是它应该很好地介绍循环算法的各种嵌套适合初学者。

        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.

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

        解决方案

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

        Java has 4 looping constructs:

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

        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:

        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-each construct, which lacks explicit indices, makes the indepedence of both loops obvious: you can swap the two for statements in the above code, and you'd still get all pairs, though listed in a different order.

        This use of a boolean method for a while loop (this one from java.util.Scanner) is typical:

        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-while is different from while-do and for:

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

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


        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.

        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 actually O(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.


        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 for loops algorithms for beginners.

        这篇关于Java中嵌套循环的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆