Java中的循环

编程语言中的循环是一种功能,它有助于在某些条件为真时重复执行一组指令/函数。 Java提供了三种执行循环的方法。虽然所有这些方法都提供类似的基本功能,但它们在语法和条件检查时间上有所不同。

null
  1. while循环: while循环是一种控制流语句,允许根据给定的布尔条件重复执行代码。while循环可以看作是一个重复的if语句。 语法:
    while (boolean condition)
    {
       loop statements...
    }
    

    流程图: while loop

    • While循环从条件检查开始。如果计算结果为true,则执行循环体语句,否则执行循环后的第一条语句。因此,它也被称为 入口控制回路
    • 条件求值为true后,将执行循环体中的语句。通常,这些语句包含下一次迭代处理的变量的更新值。
    • 当条件变为false时,循环终止,这标志着其生命周期的结束。

    // Java program to illustrate while loop
    class whileLoopDemo
    {
    public static void main(String args[])
    {
    int x = 1 ;
    // Exit when x becomes greater than 4
    while (x <= 4 )
    {
    System.out.println( "Value of x:" + x);
    // Increment the value of x for
    // next iteration
    x++;
    }
    }
    }

    
    

    输出:

    Value of x:1
    Value of x:2
    Value of x:3
    Value of x:4
    
  2. for循环: for循环提供了一种编写循环结构的简洁方法。与while循环不同,for语句在一行中使用初始化、条件和增量/减量,从而提供了一个更短、易于调试的循环结构。 语法:
    for (initialization condition; testing condition; 
                                  increment/decrement)
    {
        statement(s)
    }
    

    流程图: for-loop-in-java

    1. 初始化条件: 这里,我们初始化正在使用的变量。它标志着for循环的开始。可以使用已声明的变量,也可以声明变量,仅限于循环的局部变量。
    2. 测试条件: 它用于测试循环的退出条件。它必须返回一个布尔值。它也是一个 入口控制回路 在执行循环语句之前检查条件。
    3. 语句执行: 条件求值为true后,将执行循环体中的语句。
    4. 增量/减量: 它用于为下一次迭代更新变量。
    5. 循环终止: 当条件变为false时,循环终止,标志着其生命周期的结束。

    // Java program to illustrate for loop.
    class forLoopDemo
    {
    public static void main(String args[])
    {
    // for loop begins when x=2
    // and runs till x <=4
    for ( int x = 2 ; x <= 4 ; x++)
    System.out.println( "Value of x:" + x);
    }
    }

    
    

    输出:

    Value of x:2
    Value of x:3
    Value of x:4
    

    增强的For循环

    Java还包括Java 5中引入的for循环的另一个版本。增强的for循环提供了一种更简单的方法来遍历集合或数组的元素。它是不灵活的,只有在需要以顺序方式迭代元素时才应该使用,而不知道当前处理的元素的索引。 还请注意,当使用增强for循环时,对象/变量是不可变的,即它确保数组中的值不能修改,因此可以说它是只读循环,不能更新值,与其他可以修改值的循环相反。 我们建议尽可能使用这种形式的for语句,而不是一般形式。(根据JAVA文档) 语法:

    for (T element:Collection obj/array)
    {
        statement(s)
    }
    

    让我们举一个例子来演示如何使用增强for循环来简化工作。假设有一个名称数组,我们想打印该数组中的所有名称。让我们看看这两个例子之间的区别 增强的for-loop简化了工作,如下所示-

    // Java program to illustrate enhanced for loop
    public class enhancedforloop
    {
    public static void main(String args[])
    {
    String array[] = { "Ron" , "Harry" , "Hermoine" };
    //enhanced for loop
    for (String x:array)
    {
    System.out.println(x);
    }
    /* for loop for same function
    for (int i = 0; i < array.length; i++)
    {
    System.out.println(array[i]);
    }
    */
    }
    }

    
    

    输出:

    Ron
    Harry
    Hermoine
    
  3. 趁此机会: do while循环与while循环类似,唯一的区别是它在执行语句后检查条件,因此是 出口控制回路。 语法:
    do
    {
        statements..
    }
    while (condition);
    

    流程图: do-while

    1. do while循环从语句的执行开始。第一次没有检查任何情况。
    2. 在执行语句并更新变量值后,将检查条件的真值或假值。如果计算结果为true,则循环的下一次迭代开始。
    3. 当条件变为false时,循环终止,这标志着其生命周期的结束。
    4. 需要注意的是,do while循环在检查任何条件之前至少会执行一次语句,因此是退出控制循环的一个例子。

    // Java program to illustrate do-while loop
    class dowhileloopDemo
    {
    public static void main(String args[])
    {
    int x = 21 ;
    do
    {
    // The line will be printed even
    // if the condition is false
    System.out.println( "Value of x:" + x);
    x++;
    }
    while (x < 20 );
    }
    }

    
    

    输出:

    Value of x: 21
    

循环的陷阱

  1. 无限循环: 在实现任何类型的循环时,最常见的错误之一是,它可能永远不会退出,也就是说,循环会无限期地运行。当条件因某种原因失效时,就会发生这种情况。 例如:

    //Java program to illustrate various pitfalls.
    public class LooppitfallsDemo
    {
    public static void main(String[] args)
    {
    // infinite loop because condition is not apt
    // condition should have been i>0.
    for ( int i = 5 ; i != 0 ; i -= 2 )
    {
    System.out.println(i);
    }
    int x = 5 ;
    // infinite loop because update statement
    // is not provided.
    while (x == 5 )
    {
    System.out.println( "In the loop" );
    }
    }
    }

    
    

  2. 另一个陷阱是,您可能通过循环向集合对象中添加了一些内容,可能会耗尽内存。如果您尝试执行下面的程序,一段时间后,将抛出内存不足异常。

    //Java program for out of memory exception.
    import java.util.ArrayList;
    public class Integer1
    {
    public static void main(String[] args)
    {
    ArrayList<Integer> ar = new ArrayList<>();
    for ( int i = 0 ; i < Integer.MAX_VALUE; i++)
    {
    ar.add(i);
    }
    }
    }

    
    

    输出:

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.ArrayList.grow(Unknown Source)
    at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
    at java.util.ArrayList.add(Unknown Source)
    at article.Integer1.main(Integer1.java:9)
    

本文由 Rishabh Mahrsee .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享