В този урок ще научим как да използваме while и do while цикъл в Java с помощта на примери.
При компютърното програмиране циклите се използват за повтаряне на блок от код. Например, ако искате да покажете съобщение 100 пъти, тогава можете да използвате цикъл. Това е просто прост пример; можете да постигнете много повече с цикли.
В предишния урок научихте за Java for loop. Тук ще научите за while
и do… while
цикли.
Цикъл Java while
while
Цикълът Java се използва за изпълнение на определен код, докато се изпълни определено условие. Синтаксисът на while
цикъла е:
while (testExpression) ( // body of loop )
Тук,
- А
while
контур оценява textExpression в скобите()
. - Ако textExpression оцени като
true
, кодът вwhile
цикъла се изпълнява. - В textExpression се оценява отново.
- Този процес продължава, докато textExpression е
false
. - Когато textExpression оцени до
false
, цикълът спира.
За да научите повече за условията, посетете релационни и логически оператори на Java.
Блок-схема на цикъл while
Блок-схема на Java while loopПример 1: Показване на числа от 1 до 5
// Program to display numbers from 1 to 5 class Main ( public static void main(String() args) ( // declare variables int i = 1, n = 5; // while loop from 1 to 5 while(i <= n) ( System.out.println(i); i++; ) ) )
Изход
1 2 3 4 5
Ето как работи тази програма.
Повторение | Променлива | Състояние: i <= n | Действие |
---|---|---|---|
1-ви | i = 1 n = 5 | true | 1 се отпечатва. i се увеличава на 2 . |
2-ри | i = 2 n = 5 | true | 2 се отпечатва. i се увеличава до 3 . |
3-ти | i = 3 n = 5 | true | 3 се отпечатва. i се увеличава на 4 . |
4-ти | i = 4 n = 5 | true | 4 се отпечатва. i се увеличава на 5 . |
5-ти | i = 5 n = 5 | true | 5 се отпечатва. i се увеличава на 6 . |
6-то | i = 6 n = 5 | false | Цикълът е прекратен |
Пример 2: Сума само на положителни числа
// Java program to find the sum of positive numbers import java.util.Scanner; class Main ( public static void main(String() args) ( int sum = 0; // create an object of Scanner class Scanner input = new Scanner(System.in); // take integer input from the user System.out.println("Enter a number"); int number = input.nextInt(); // while loop continues // until entered number is positive while (number>= 0) ( // add only positive numbers sum += number; System.out.println("Enter a number"); number = input.nextInt(); ) System.out.println("Sum = " + sum); input.close(); ) )
Изход
Въведете число 25 Въведете число 9 Въведете число 5 Въведете число -3 Сума = 39
В горната програма използвахме класа Scanner, за да вземем данни от потребителя. Тук nextInt()
взема целочислено въвеждане от потребителя.
В while
цикълът продължава, докато потребителят въведе редица отрицателни. По време на всяка итерация номерът, въведен от потребителя, се добавя към sum
променливата.
Когато потребителят въведе отрицателно число, цикълът се прекратява. Накрая се показва общата сума.
Java do … while цикъл
В do… while
бримката е подобен докато линия. Тялото на do… while
цикъла обаче се изпълнява веднъж, преди да се провери тестовият израз. Например,
do ( // body of loop ) while(textExpression)
Тук,
- Първо се изпълнява тялото на цикъла. След това се оценява textExpression .
- Ако textExpression оценява на
true
, тялото на цикъла вътре вdo
оператора се изпълнява отново. - В textExpression се оценява още веднъж.
- Ако textExpression оценява на
true
, тялото на цикъла вътре вdo
оператора се изпълнява отново. - Този процес продължава, докато textExpression оцени до
false
. След това цикълът спира.
Блок-схема на цикъл do … while
Блок-схема на Java, докато цикълLet's see the working of do… while
loop.
Example 3: Display Numbers from 1 to 5
// Java Program to display numbers from 1 to 5 import java.util.Scanner; // Program to find the sum of natural numbers from 1 to 100. class Main ( public static void main(String() args) ( int i = 1, n = 5; // do… while loop from 1 to 5 do ( System.out.println(i); i++; ) while(i <= n); ) )
Output
1 2 3 4 5
Here is how this program works.
Iteration | Variable | Condition: i <= n | Action |
---|---|---|---|
i = 1 n = 5 | not checked | 1 is printed. i is increased to 2. |
|
1st | i = 2 n = 5 | true | 2 is printed. i is increased to 3. |
2nd | i = 3 n = 5 | true | 3 is printed. i is increased to 4. |
3rd | i = 4 n = 5 | true | 4 is printed. i is increased to 5. |
4th | i = 5 n = 5 | true | 6 is printed. i is increased to 6. |
5th | i = 6 n = 5 | false | The loop is terminated |
Example 4: Sum of Positive Numbers
// Java program to find the sum of positive numbers import java.util.Scanner; class Main ( public static void main(String() args) ( int sum = 0; int number = 0; // create an object of Scanner class Scanner input = new Scanner(System.in); // do… while loop continues // until entered number is positive do ( // add only positive numbers sum += number; System.out.println("Enter a number"); number = input.nextInt(); ) while(number>= 0); System.out.println("Sum = " + sum); input.close(); ) )
Output 1
Enter a number 25 Enter a number 9 Enter a number 5 Enter a number -3 Sum = 39
Here, the user enters a positive number, that number is added to the sum variable. And this process continues until the number is negative. When the number is negative, the loop terminates and displays the sum without adding the negative number.
Output 2
Enter a number -8 Sum is 0
Here, the user enters a negative number. The test condition will be false
but the code inside of the loop executes once.
Infinite while loop
If the condition of a loop is always true
, the loop runs for infinite times (until the memory is full). For example,
// infinite while loop while(true)( // body of loop )
Here is an example of an infinite do… while
loop.
// infinite do… while loop int count = 1; do ( // body of loop ) while(count == 1)
In the above programs, the textExpression is always true
. Hence, the loop body will run for infinite times.
for and while loops
В for
линия се използва, когато е известен брой повторения. Например,
for (let i = 1; i <=5; ++i) ( // body of loop )
Обикновено циклите and while
и do… while
се използват, когато броят на итерациите е неизвестен. Например,
while (condition) ( // body of loop )