Java 程序:while
循环
原文:https://www.studytonight.com/java-programs/java-while-loop-program
在本教程中,我们将学习如何在不同的场景中实现 while 循环。但是在继续之前,如果你不熟悉 while loop 的概念,那么一定要查看一下 Java 中Loops的文章。
循环时的语法
while(condition)
{
//Code to be executed
}
Java 程序:程序 1:实现 While 循环
在这个程序中,我们将看到如何在 java 中实现 while 循环程序。在这里,我们将考虑一个场景,我们将找到一个特定数字的乘法表。我们将对相同的元素使用 while 循环,而不是为每个元素编写乘法表。我们将编写一次语句,并多次实现。
算法
开始
创建 Scanner 类的实例。
宣布一个数字
要求用户初始化数字。
使用 while 循环打印该数字的乘法表。
显示结果。
停下来。
下面是 while 循环的 Java 代码。
//Java Program to see the implementation while loop program
import java.util.*;
public class Main
{
public static void main(String []args)
{
//Take input from the user
//Create instance of the Scanner Class
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int n=sc.nextInt(); //Declare and initialize the number
int i=1;
System.out.println("The multiplication table of "+n+" is: ");
//Infinite Loop Example
while(i<=10)
{
System.out.println(n+" * "+i+" = "+ (n*i));
i++;
}
}
}
输入数字:3 3 的乘法表为: 3 1 = 3 3 2 = 6 3 3 = 9 3 4 = 12 3 5 = 15 3 6 = 18 3 7 = 21 3 8 = 24 3 9 = 27 3 10 = 30
Java 程序:程序 2:实现 While 循环
在这个程序中,如何使用 while 循环找到所有输入的正数的和。
算法:
开始
创建 Scanner 类的实例。
声明一个变量。
要求用户初始化变量。
声明另一个变量来存储所有正数的和。
将其初始化为 0。
使用 while 循环检查输入的数字是否为正数。
每次输入正数时增加总和。
如果输入了任何负数,请中断循环。
显示总和。
停下来。
下面是 while 循环的 Java 代码。
//Java Program to calculate the sum of entered positive numbers using a while loop
import java.util.*;
public class Main
{
public static void main(String []args)
{
//Take input from the user
//Create instance of the Scanner Class
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int n=sc.nextInt(); //Declare and initialize the number
int sum=0;
//While loop will take values only if the numbers are positive
while (n >= 0)
{
// add only positive numbers
sum += n;
System.out.println("Enter the number:");
n = sc.nextInt();
}
System.out.println("Sum of the entered positive numbers = " + sum);
}
}
输入数字:3 输入数字:4 输入数字:3 输入数字:2 输入数字:1 输入数字:-9 输入正数之和= 13
Java 程序:程序 3:实现 While 循环
在这个程序中,我们将看到如何使用 while 循环无限次地执行某个任务。为此,我们将在 while 循环的条件语句中传递 true。这样做会使它成为一个不定式 while 循环。这里需要注意的一点是,为了退出无限循环,您需要按 ctrl+c。
算法:
开始
声明一个变量。
将其初始化为 1。
在 while 循环的条件下传递 true。
执行该语句,直到条件为假。
在每次迭代中增加变量。
显示结果。
停下来。
下面是 while 循环的 Java 代码。
//Java Program for the implementation of a while loop
public class Main
{
public static void main(String []args)
{
int i=1;
//If true is passed in a while loop, then it will be infinitive while loop.
while (true)
{
System.out.println(i + " Hello World!");
i++;
}
}
}
1 你好世界! 2 你好世界! 3 你好世界! 4 你好世界! 5 你好世界! 6 你好世界! 7 你好世界! ctrl+c