编程基础:Java中的循环语句用法详细指南

2021年4月2日11:17:35 发表评论 988 次浏览

编程语言中的循环是一项功能, 可在某些条件评估为真时, 促进重复执行一组指令/功能。

Java提供了三种执行循环的方法。尽管所有方式都提供相似的基本功能, 但是它们的语法和条件检查时间有所不同。

while循环:

while循环是一个控制流语句, 它允许根据给定的布尔条件重复执行代码。 while循环可被视为重复的if语句。

句法 :

while (boolean condition)
{
   loop statements...
}

流程图:

while循环
  • While循环从条件检查开始。如果评估结果为true, 则执行循环主体语句, 否则执行循环之后的第一条语句。因此, 它也被称为进入控制回路
  • 一旦条件评估为真, 就执行循环主体中的语句。通常, 语句包含下一个迭代要处理的变量的更新值。
  • 当条件变为假时, 循环终止, 标志着其生命周期的结束。
// 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

for循环

for循环提供了编写循环结构的简洁方法。与while循环不同, for语句在一行中消耗了初始化, 条件和增量/减量, 从而提供了更短, 更易于调试的循环结构。

语法如下:

for (initialization condition; testing condition; 
                              increment/decrement)
{
    statement(s)
}

流程图:

Java中的循环
  1. 初始化条件:在这里, 我们初始化使用中的变量。它标志着for循环的开始。可以使用已经声明的变量, 也可以声明一个变量, 仅局部于循环。
  2. 测试条件:用于测试循环的退出条件。它必须返回一个布尔值。这也是进入控制回路因为条件是在执行循环语句之前检查的。
  3. 语句执行:一旦条件评估为真, 就执行循环主体中的语句。
  4. 增/减:它用于更新变量以进行下一次迭代。
  5. 循环终止:当条件变为假时, 循环终止, 标志其生命周期的结束。
// 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循环简化了以下工作:

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

do-while循环

do while循环与while循环类似,唯一不同的是它在执行语句后检查条件,因此是退出控制循环的一个例子。

语法如下:

do
{
    statements..
}
while (condition);

流程图:

do-while循环
  1. do while循环从语句的执行开始。第一次没有检查任何条件。
  2. 在执行语句并更新变量值之后, 将检查条件的真值或假值。如果计算结果为true, 则循环的下一个迭代开始。
  3. 当条件变为假时, 循环终止, 标志着其生命周期的结束。
  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

循环陷阱

无限循环:

实现任何形式的循环时, 最常见的错误之一是它可能永远不会退出, 即循环会无限期地运行。当条件由于某种原因失败时, 就会发生这种情况。

例子:

//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" );
         }
     }
}

另一个陷阱是, 你可能会通过循环将某些东西添加到你的集合对象中, 从而可能耗尽内存。如果尝试执行以下程序, 则一段时间后, 将抛出内存不足异常。

//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)

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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: