- Branching Statements
- The continue Statement
- The return Statement
- Выход из цикла while в Java
- Выйти из цикла while после завершения выполнения программы на Java
- Выйдите из цикла while с помощью break в Java
- Выйдите из цикла while с помощью return в Java
- Сопутствующая статья — Java Loop
- Java while Loop
- Циклы в Java – как создать и прервать
- Вложенные циклы Java
Branching Statements
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for , while , or do-while loop, as shown in the following BreakDemo program:
class BreakDemo < public static void main(String[] args) < int[] arrayOfInts = < 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 >; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) < if (arrayOfInts[i] == searchfor) < foundIt = true; break; > > if (foundIt) < System.out.println("Found " + searchfor + " at index " + i); >else < System.out.println(searchfor + " not in the array"); >> >
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program’s output is:
An unlabeled break statement terminates the innermost switch , for , while , or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo , is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled «search»):
class BreakWithLabelDemo < public static void main(String[] args) < int[][] arrayOfInts = < < 32, 87, 3, 589 >, < 12, 1076, 2000, 8 >, < 622, 127, 77, 955 >>; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) < for (j = 0; j < arrayOfInts[i].length; j++) < if (arrayOfInts[i][j] == searchfor) < foundIt = true; break search; >> > if (foundIt) < System.out.println("Found " + searchfor + " at " + i + ", " + j); >else < System.out.println(searchfor + " not in the array"); >> >
This is the output of the program.
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for , while , or do-while loop. The unlabeled form skips to the end of the innermost loop’s body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String , counting the occurrences of the letter «p». If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a «p», the program increments the letter count.
class ContinueDemo < public static void main(String[] args) < String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) < // interested only in p's if (searchMe.charAt(i) != 'p') continue; // process p's numPs++; >System.out.println("Found " + numPs + " p's in the string."); > >
Here is the output of this program:
To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p’s instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo , uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo , uses the labeled form of continue to skip an iteration in the outer loop.
class ContinueWithLabelDemo < public static void main(String[] args) < String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i > foundIt = true; break test; > System.out.println(foundIt ? "Found it" : "Didn't find it"); > >
Here is the output from this program.
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn’t. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
The data type of the returned value must match the type of the method’s declared return value. When a method is declared void , use the form of return that doesn’t return a value.
The Classes and Objects lesson will cover everything you need to know about writing methods.
Выход из цикла while в Java
- Выйти из цикла while после завершения выполнения программы на Java
- Выйдите из цикла while с помощью break в Java
- Выйдите из цикла while с помощью return в Java
В этом руководстве показано, как выйти из цикла while в Java и обработать его с помощью некоторых примеров кода, которые помогут вам лучше понять тему.
Цикл while — это один из циклов Java, используемых для итерации или повторения операторов до тех пор, пока они не будут соответствовать указанному условию. Чтобы выйти из цикла while, вы можете использовать следующие методы:
- Выход после завершения цикла в обычном режиме
- Выйти с помощью оператора break
- Выйти с помощью оператора return
Выйти из цикла while после завершения выполнения программы на Java
Этот метод представляет собой простой пример, в котором цикл while завершается сам по себе после того, как указанное условие помечается как false .
Цикл while выполняется повторно до тех пор, пока указанное условие не станет true , и завершится, если условие false . См. Пример ниже, где мы перебираем элементы списка с помощью цикла while и получаем выход из цикла, когда все элементы пройдены.
import java.util.Arrays; import java.util.List; public class SimpleTesting public static void main(String[] args) ListInteger> list = Arrays.asList(new Integer[]12,34,21,33,22,55>); int i = 0; while(ilist.size()) System.out.println(list.get(i)); i++; > > >
Выйдите из цикла while с помощью break в Java
Это еще одно решение, в котором мы использовали оператор break для выхода из цикла. Оператор break используется для прерывания текущего потока выполнения, и управление выходит за пределы цикла, что приводит к выходу из цикла между ними. Вы можете использовать break для явного выхода из цикла while. См. Пример ниже:
import java.util.Arrays; import java.util.List; public class SimpleTesting public static void main(String[] args) ListInteger> list = Arrays.asList(new Integer[]12,34,21,33,22,55>); int i = 0; while(ilist.size()) if(i == 3) break; System.out.println(list.get(i)); i++; > > >
Выйдите из цикла while с помощью return в Java
Java использует оператор return для возврата ответа вызывающему методу, и управление немедленно передается вызывающему, выходя из цикла (если он существует). Таким образом, мы можем использовать return и для выхода из цикла while. Посмотрите код ниже, чтобы увидеть, как мы использовали return .
import java.util.Arrays; import java.util.List; public class SimpleTesting public static void main(String[] args) boolean result = show(); if(result) System.out.println("Loop Exit explicitly"); >else System.out.println("Loop not exit explicitly"); > static boolean show() ListInteger> list = Arrays.asList(new Integer[]12,34,21,33,22,55>); int i = 0; while(ilist.size()) if(i == 3) return true; System.out.println(list.get(i)); i++; > return false; > >
12 34 21 Loop Exit explicitly
Сопутствующая статья — Java Loop
Java while Loop
The while loop in Java continually executes a block of statements until a particular condition evaluates to true. As soon as the condition becomes false , the while loop terminates.
As a best practice, if the number of iterations is not known at the start, it is recommended to use the while loop.
The syntax of while loop is:
while (condition-expression)
The condition-expression must be a boolean expression and the statements can be one simple statement or a block of multiple statements. Every time the condition-expression evaluates to true , statement(s) block is executed.
The while statement continues testing the condition-expression in loop and executing the block until the condition-expression evaluates to false.
- The execution starts with the evaluation of the condition-expression .
- If the condition is evaluated to true , statements block is executed. This is called an iteration.
- An iteration happens everytime the condition is true .
- When the condition is evaluated to false , the loop is terminated immediately.
Let us understand the while loop with a few examples.
2.1. Print all numbers from 1 to N
To print all integers between 1 and 5 using a while-loop, we can create a condition on a local variable counter that must not be less than or equal to 5.
As soon as, the counter reaches 6, the loop terminates.
int counter = 1; while (counter
2.2. Iterate through a List
The following Java program iterates over an ArrayList using its iterator in the while loop.
List list = List.of("A", "B", "C"); Iterator iterator = list.iterator(); while (iterator.hasNext())
2.3. Iterate through an Array
To iterate over array, we should create the condition on array length. We need to iterate over all array elements using the index counter.
Once index reaches is equal to the length of the array, the while loop terminates.
Integer[] array = new Integer[] ; int index = 0; while (index
Programmers makes mistake. If the conditional-expression given in while loop never terminates then the loop will result in an infinite while-loop. For example, in the previous program, if the index value is not incremented after each iteration, then the condition will never terminate.
In the next example, index start with 0 and check if it is less than the array length. As we are not incrementing its value, it will always be less than 5, no matter how many iterations happen. This loop is an infinite loop.
Integer[] array = new Integer[] ; int index = 0; while (index < array.length) //Infinite Loop because we are not incrementing the index
The infinite loops, sometimes, result into StackOverflowError or OutOfMemoryError based on what we are trying to do in the loop. If there are no memory leaks, it is possible that the loop never terminates and executes infinitely. The program will hang in this situation.
4. Difference between While-loop and For-loop
Unlike the for-loop statement, the condition-expression in while loop statement is not optional. In general, a for-loop statement can be converted to a while-loop statement. However, not all for-loop statements can be converted to a while-loop statement.
The following is a pseudo-code for writing a simple for loop.
for (initialization; condition-expression; expression-list)
We can write the equivalent program using the while loop as follows:
initialization; while (condition-expression)
5. While loop with break Keyword
A break statement is used to exit the loop in a while-loop statement. It is helpful in terminating the loop if a certain condition evaluates during the execution of the loop body.
int i = 1; while (true) // Cannot exit the loop from here < if (i else < break; // Exit the loop >>
Simple, right? Practice it more by creating a few more programs around while loop statement.
Циклы в Java – как создать и прервать
Как в Java создавать циклы и управлять ими. Как с их помощью автоматизировать обработку массивов и генерацию объектов.
Цикл — это блок команд, который выполняется снова и снова, пока соблюдается определённое условие. Повторяемый фрагмент кода называют «телом цикла». Одно выполнение тела цикла называют итерацией.
В Яве можно работать с циклами нескольких типов - для этого есть следующие операторы:
while – цикл с предусловием – сначала проверяем условие, затем выполняем тело цикла;
do… while – цикл с постусловием – сначала выполняем один раз тело цикла, затем проверяем условие и, если оно соблюдается, продолжаем;
for – цикл со счётчиком – выполняется и при каждой итерации обновляет счётчик, пока условие в объявлении цикла соблюдается (т.е. проверка условия возвращает true);
сокращенный for (в других языках известен как foreach) – перебирает массив от первого элемента до последнего и на каждой итерации выполняет тело цикла.
Если мы используем конструкции с while, значение нужно указать перед началом цикла:
System.out.println(a);
a++; //увеличиваем а на единицу
Если же переменная работает как счётчик цикла, а за его пределами не используется, её инициализируют прямо в условии. И тут же пишут, что с ней делать в конце каждой итерации. Всё это – в одну строку – с помощью for:
System.out.println(a);
Получаем тот же результат. Список можно было начать с нуля или с отрицательного значения – диапазон определяем сами.
Сокращенный вариант цикла for не содержит указаний ни на число повторов, ни на действия в конце шага. Цикл типа foreach используют для перебора массивов. От первого элемента нужно переходить к следующему – пока массив не кончится.
int[] ms = < 1, 2, 3, 4>; //создаем массив
s *= i; //последовательно перемножаем элементы
System.out.println(s);
Вложенные циклы Java
Циклы можно вкладывать один в другой. При этом число повторов наружного и вложенных циклов умножается. Если внешний должен выполняться 5 раз и внутренний – 5, всего цикл будет выполнен 25 раз.
Выведем таблицу умножения с помощью двух массивов:
int a, b, result = 0;