Java中的while循环——通过示例学习Java编程(10)

作者:CHAITANYA SINGH

来源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid=20

在上一个教程中,我们讨论了for循环的用法。在本教程中,我们将讨论while循环的用法。如前一个教程中所讨论的,循环用于重复执行同一组语句,直到某个特定条件满足后,程序就跳出这个循环。

while循环的语法:

1
2
3
4
while (condition)
{
    statement(s);
}

while循环是如何工作的?

在while循环中,首先评估while后面的括号里面循环条件,如果评估循环条件返回的值是true(真),则程序继续执行while循环中的语句。如果评估循环条件返回的值是,程序就跳出循环,执行while循环代码块外面的下一个语句。

注意:使用while循环的代码块里面,一定要正确的对循环变量使用递增或递减语句,这样循环变量的值在每次循环时都会更新,当循环变量的值更新到某个值的时候,while后面的循环条件的评估会返回false值(假),这个时候程序就会跳出循环。如果循环变量的值递增或递减语句写得不对,while后面的循环条件永远都是返回true值,这样的话程序永远也不会跳出while循环的代码块,这是循环就进入了一个死循环。

while循环示例(简单版):

1
2
3
4
5
6
7
8
9
class  WhileLoopExample {
     public  static  void  main(String args[]){
          int  i= 10 ;
          while (i> 1 ){
               System.out.println(i);
               i--;
          }
     }
}

输出:

1
2
3
4
5
6
7
8
9
10
9
8
7
6
5
4
3
2

while循环示例(死循环):

1
2
3
4
5
6
7
8
9
10
class  WhileLoopExample2 {
     public  static  void  main(String args[]){
          int  i= 10 ;
          while (i> 1 )
          {
              System.out.println(i);
               i++;
          }
     }
}

在while后面的括号里面的循环条件是i>1,因为i的初始值是10(>1),在循环代码里面又不停地给i的值进行递增(i++)操作,i的值会越来越大,这样循环条件(i>1)永远返回的值都是true(真),所以程序永远不会跳出这个循环,这个循环是一个死循环。

下面是另一个死循环的示例:

1
2
3
while  ( true ){
     statement(s);
}

while循环示例(遍历数组元素):

在这里,我们使用while循环来遍历和显示数组(array)里面的每个元素。

1
2
3
4
5
6
7
8
9
10
11
class  WhileLoopExample3 {
     public  static  void  main(String args[]){
          int  arr[]={ 2 , 11 , 45 , 9 };
          //i starts with 0 as array index starts with 0 too
          int  i= 0 ;
          while (i< 4 ){
               System.out.println(arr[i]);
               i++;
          }
     }
}

输出:

1
2
3
4
2
11
45
9

猜你喜欢

转载自www.cnblogs.com/lea1941/p/10863715.html