21xrx.com
2024-04-25 20:07:00 Thursday
登录
文章检索 我的文章 写文章
Java while 循环
2021-07-08 16:17:52 深夜i     --     --
J a v a h i l e

在 Java 中,while 循环用于执行语句,直到条件为真。 在本教程中,我们将学习如何通过示例使用它。 首先,让我们讨论一下它的语法:

while (condition(s)) { // 循环体}

1. 如果条件成立,则在循环体条件的执行被再次测试后执行循环体。 如果条件仍然成立,则再次执行循环体,并重复该过程直到条件变为假。 条件的计算结果为真或假,如果它是一个常数,例如,while (x) {…},其中 x 是一个常数,那么任何 'x' 的非零值计算为真,零为假。

 

2. 可以测试多个条件,例如

while (a > b && c != 0) {
 // Loop body
}

循环体一直执行,直到变量 a 的值大于变量 b 的值并且变量 c 不等于 0。

3. 一个循环体可以包含多个语句。 对于多个语句,您需要使用 {} 将它们放在一个块中。 如果正文仅包含一条语句,您可以选择使用 {}。 始终建议使用大括号使您的程序易于阅读和理解。

 

Java while 循环示例

以下程序要求用户输入一个整数并打印它,直到用户输入 0(零)。

import java.util.Scanner;


class WhileLoop {
  public static void main(String[] args) {
    int n;
   
    Scanner input = new Scanner(System.in);
    System.out.println("Input an integer");
   
    while ((n = input.nextInt()) != 0) {
      System.out.println("You entered " + n);
      System.out.println("Input an integer");
    }
   
    System.out.println("Out of loop");
  }
}

程序输出:

 

Java while 循环中断程序

 

我们可以使用 break 语句编写上述程序。 我们测试用户输入,如果它为零,那么我们使用“break”退出或退出循环。

import java.util.Scanner;


class BreakWhileLoop {
  public static void main(String[] args) {
    int n;
   
    Scanner input = new Scanner(System.in);
   
    while (true) { // Condition in while loop is always true here
      System.out.println("Input an integer");
      n = input.nextInt();
     
      if (n == 0) {
        break;
      }
      System.out.println("You entered " + n);
    }
  }
}

Java while 循环中断继续程序

import java.util.Scanner;


class BreakContinueWhileLoop {
  public static void main(String[] args) {
    int n;
   
    Scanner input = new Scanner(System.in);
   
    while (true) {
      System.out.println("Input an integer");
      n = input.nextInt();
     
      if (n != 0) {
        System.out.println("You entered " + n);
        continue;
      }
      else {
        break;
      }
    }
  }
}

Continue 语句控制循环的开始,然后循环体再次执行。 无论您可以使用 while 循环做什么,都可以使用 for 循环或 do-while 循环来完成。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复