Остановить цикл while 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

  1. Выйти из цикла while после завершения выполнения программы на Java
  2. Выйдите из цикла while с помощью break в Java
  3. Выйдите из цикла while с помощью return в Java
Читайте также:  Java constructor using reflection

В этом руководстве показано, как выйти из цикла 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 – как создать и прервать

Как в 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;

Источник

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