Java while true break

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.

Читайте также:  Source code for python modules

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.

Источник

Выход из цикла while в Java

Выход из цикла while в Java

  1. Выйти из цикла while после завершения выполнения программы на Java
  2. Выйдите из цикла while с помощью break в Java
  3. Выйдите из цикла 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

Источник

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.

Источник

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