While внутри while java

Java while Loops

The Java while loop is similar to the for loop. The while loop enables your Java program to repeat a set of operations while a certain conditions is true.

The Java while loop exist in two variations. The commonly used while loop and the less often do while version. I will cover both while loop versions in this text.

The Java while Loop

Let us first look at the most commonly used variation of the Java while loop. Here is a simple Java while loop example:

int counter = 0; while(counter

This example shows a while loop that executes the body of the loop as long as the counter variable is less than 10. Inside the while loop body the counter is incremented. Eventually the counter variable will no longer be less than 10, and the while loop will stop executing.

Here is another while example that uses a boolean to make the comparison:

boolean shouldContinue = true; while(shouldContinue == true) < System.out.println("running"); double random = Math.random() * 10D; if(random >5) < shouldContinue = true; >else < shouldContinue = false; >>

This Java while example tests the boolean variable shouldContinue to check if the while loop should be executed or not. If the shouldContinue variable has the value true , the while loop body is executed one more time. If the shouldContinue variable has the value false , the while loop stops, and execution continues at the next statement after the while loop.

Читайте также:  Ansible windows install python

Inside the while loop body a random number between 0 and 10 is generated. If the random number is larger than 5, then the shouldContinue variable will be set to true . If the random number is 5 or less, the shouldContinue variable will be set to false .

Like with for loops, the curly braces are optional around the while loop body. If you omit the curly braces then the while loop body will consist of only the first following Java statement. Here is a Java while example illustrating that:

while(iterator.hasNext()) System.out.println("next: " + iterator.next()); // executed in loop System.out.println("second line"); // executed after loop

In this example, only the first System.out.println() statement is executed inside the while loop. The second System.out.println() statement is not executed until after the while loop is finished.

Forgetting the curly braces around the while loop body is a common mistake. Therefore it can be a good habit to just always put them around the while loop body.

The Java do while Loop

The second variation of the Java while loop is the do while construct. Here is a Java do while example:

InputStream inputStream = new FileInputStream("data/text.xml"); int data; do < data = inputStream.read(); >while(data != -1);

Notice the while loop condition is now moved to after the do while loop body. The do while loop body is always executed at least once, and is then executed repeatedly while the while loop condition is true .

The main difference between the two while loop variations is exactly that the do while loop is always executed at least once before the while loop condition is tested. This is not the case with the normal while loop variation explained in the beginning of this text.

The two variations of the Java while loop come in handy in different situations. I mostly used the first while loop variation, but there are situations where I have used the second variation.

The continue Command

Java contains a continue command which can be used inside Java while (and for ) loops. The continue command is placed inside the body of the while loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the while loop body. The next iteration of the while loop body will proceed as any other. If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth.

Here is a simple continue example inside a while loop:

String[] strings = < "John", "Jack", "Abraham", "Jennifer", "Ann" >; int wordsStartingWithJ = 0; int i=0; while( i < strings.length ) < if(! strings[i].toLowerCase().startsWith("j")) < i++; continue; >wordsStartingWithJ++; i++; >

Notice the if statement inside the while loop. This if statement checks if each String in the strings array does not start with with the letter j . If not, then the continue command is executed, and the while loop continues to the next iteration.

If the current String in the strings array does start with the letter j , then the next Java statement after the if statement is executed, and the variable wordsStartingWithJ is incremented by 1.

The continue command also works inside do while loops. Here is a do while version of the previous example:

String[] strings = < "John", "Jack", "Abraham", "Jennifer", "Ann" >; int wordsStartingWithJ = 0; int i=0; do < if(! strings[i].toLowerCase().startsWith("j")) < i++; continue; >wordsStartingWithJ++; i++; > while( i < strings.length );

Notice that this version of the while loop requires that the strings array has a least one element, or it will fail when trying to index into the array at position 0 during the first iteration of the do while loop.

The break Command

The break command is a command that works inside Java while (and for ) loops. When the break command is met, the Java Virtual Machine breaks out of the while loop, even if the loop condition is still true. No more iterations of the while loop are executed once a break command is met. Here is a break command example inside a while loop:

String[] strings = < "John", "Jack", "Abraham", "Jennifer", "Ann" >; int wordsStartingWithJ = 0; int i=0; while(i < strings.length; ) < if(strings[i].toLowerCase().startsWith("j")) < wordsStartingWithJ++; >if(wordsStartingWithJ >= 3) < break; >i++; >

Notice the second if statement inside the while loop. This if statement checks if 3 words or more have been found which starts with the letter j . If yes, the break command is executed, and the program breaks out of the while loop.

Like with the continue command, the break command also works inside do while loops. Here is the example from before, using a do while loop instead:

String[] strings = < "John", "Jack", "Abraham", "Jennifer", "Ann" >; int wordsStartingWithJ = 0; int i=0; do < if(strings[i].toLowerCase().startsWith("j")) < wordsStartingWithJ++; >if(wordsStartingWithJ >= 3) < break; >i++; > while( i < strings.length; )

Note that this variation of the while loop requires that the strings array always has at least one element. If not, it will fail during the first iteration of the do while loop, when it tries to access the first element (with index 0) of the array.

Variable Visibility in while Loops

Variables declared inside a Java while loop are only visible inside the while loop body. Look at this while loop example:

After the while loop body has finished executing the count variable is still visible, since the count variable is declared outside the while loop body. But the name variable is not visible because it is declared inside the while loop body. Therefore the name variable is only visible inside the while loop body.

Источник

Вложенный цикл в Java (с примерами)

В этом руководстве мы узнаем о вложенных циклах в Java с помощью примеров.

Если цикл существует внутри тела другого цикла, он называется вложенным циклом. Вот пример вложенного for цикла.

// outer loop for (int i = 1; i 

Здесь мы используем for цикл внутри другого for цикла.

Мы можем использовать вложенный цикл для перебора каждого дня недели в течение 3 недель.

В этом случае мы можем создать цикл для трехкратного повторения (3 недели). А внутри цикла мы можем создать еще один цикл, который будет повторяться 7 раз (7 дней).

Пример 1: Java, вложенная в цикл

class Main ( public static void main(String() args) ( int weeks = 3; int days = 7; // outer loop prints weeks for (int i = 1; i 
Неделя: 1 День: 1 День: 2 День: 3…. Неделя: 2 День: 1 День: 2 День: 3….….

В приведенном выше примере внешний цикл повторяется 3 раза и печатает 3 недели. И внутренний цикл повторяется 7 раз и выводит 7 дней.

Мы также можем создавать вложенные циклы с помощью while и do… while аналогичным образом.

Примечание . Можно использовать один тип цикла внутри тела другого цикла. Например, мы можем поместить for петлю внутрь while петли.

Пример 2: цикл for в Java внутри цикла while

class Main ( public static void main(String() args) ( int weeks = 3; int days = 7; int i = 1; // outer loop while (i 
Неделя: 1 День: 1 День: 2 День: 3…. Неделя: 2 День: 1 День: 2 День: 3….….

Здесь вы можете видеть, что результат как в примере 1, так и в примере 2 одинаков.

Пример 3: вложенные циклы Java для создания шаблона

Мы можем использовать вложенный цикл в Java для создания шаблонов, таких как полная пирамида, полупирамида, перевернутая пирамида и так далее.

Вот программа для создания узора полупирамиды с использованием вложенных петель.

class Main ( public static void main(String() args) ( int rows = 5; // outer loop for (int i = 1; i 
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Чтобы узнать больше, посетите программу Java для печати пирамид и узоров.

прервать и продолжить внутри вложенных циклов

Когда мы используем break оператор внутри внутреннего цикла, он завершает внутренний цикл, но не внешний. Например,

class Main ( public static void main(String() args) ( int weeks = 3; int days = 7; // outer loop for(int i = 1; i 
Неделя: 1 День: 1 День: 2…. Неделя: 2 Неделя: 3 День: 1 День: 2….….

В приведенном выше примере мы использовали оператор break внутри внутреннего for цикла. Здесь программа пропускает цикл, когда i равно 2 .

Следовательно, дни недели 2 не печатаются. Однако внешний цикл, печатающий неделю, не изменяется.

Точно так же, когда мы используем continue оператор внутри внутреннего цикла, он пропускает только текущую итерацию внутреннего цикла. Внешний цикл не изменяется. Например,

class Main ( public static void main(String() args) ( int weeks = 3; int days = 7; // outer loop for(int i = 1; i 
Неделя: 1 Дней: 2 Дня: 4 Дней: 6 Неделя: 2 Дней: 2 Дней: 4 Дней: 6 Неделей: 3 Дней: 2 Дней: 4 Дней: 6

В приведенном выше примере мы использовали оператор continue внутри внутреннего цикла for. Обратите внимание на код,

Здесь continue оператор выполняется, когда значение j нечетное. Таким образом, программа печатает только те дни, которые являются четными.

Мы видим, что continue оператор затронул только внутренний цикл. Внешний цикл работает без проблем.

Источник

Оцените статью