Java How to Check a Condition Then Run Through a Loop Again

While loop in Coffee: provisional loop that repeats the code multiple times

Keywords: while loop, conditional loop, iterations sets

Learn programming Java Python

This article will await at the while loop in Java which is a conditional loop that repeats a code sequence until a certain condition is met. We volition showtime past looking at how the while loop works and then focus on solving some examples together.

While loop in Java

The while loop in Java is a and then-called condition loop. This ways repeating a code sequence, over and once again, until a condition is met. In other words, you utilize the while loop when you want to echo an functioning as long as a condition is met. Instead of having to rewrite your code several times, nosotros tin can instead repeat a lawmaking block several times. In general, it can be said that a while loop in Java is a repetition of ane or more sequences that occurs as long as i or more conditions are met.

The while loop evaluates expression, which must return a boolean value. If the expression evaluates to true, the while loop executes thestatement(s) in the code cake. The while loop continues testing the expression and executing its block until the expression evaluates to false.

Oracle

How while loop in Coffee works?

The while loop is used to iterate a sequence of operations several times. In other words, you repeat parts of your program several times, thus enabling general and dynamic applications considering lawmaking is reused any number of times. If the number of iterations not is fixed, it'south recommended to employ a while loop.

The catamenia chart in Effigy ane below shows the functions of a while loop

While loop Java Programming

Figure ane: While loop in Java

Let's break it downwardly

  1. The code sequence begins at Outset and and so checks if the loop conditions are met.
  2. If the condition is met, true, the program performs the performance.
  3. When these operations are completed, the code will render to the while condition.
  4. The loop and then repeats this process until the status is simulated, and then the program continues.

In short, the while loop in java:

  • Is a loop that repeats a sequence of operations an arbitrary number of times.
  • Repeats the operations as long as a condition is true.
  • Enables general and dynamic applications because code can be reused.
  • Best suited when the number of iterations of the loop is not fixed.

How to create a while loop in Java

While loop in Coffee:

  • Yous create the while loop with the reserved word while, followed by a condition in parentheses ( )
  • Within the curly brackets, { }, you specify all operations that yous want to execute every bit long equally the condition is true.
  • The loop repeats itself until the condition is no longer met, that is, simulated.

Syntax: Declare while loop in Java

If we use the elements in the list above and insert in the code editor:

while (status) {                 // While loop code block }

Examples: While loop in Java

Let's see a few examples of how to use a while loop in Java.

Instance 1: Create a while loop in Java

The post-obit examples prove how to use the while loop to perform ane or more than operations as long a the status is true.

public grade Example{    public static void master(Cord[] args) {           int i = 0;                                         // As long equally the "i" is less than 5, the loop is executed       while(i < 5){                                        System.out.println("Hello, Earth!");                  // Increase the variable each step, i = i + i          i++;                                           }    }    }

Furthermore, in this example, nosotros print Hello, World! as long as the status is true, in other words, equally long as the variable i is less than 5. The plan will thus print the text line How-do-you-do, World! five times then end the while loop:

Howdy, World! Hello, Earth! Hullo, World! Howdy, Globe! Hello, World!

Notation, what would accept happened if i++ had not been in the loop? Thats right, since the status will ever be true (zip is always smaller than v), the while loop will never end. The plan will and then impress Howdy, World! forever. This is a so-called infinity loop that nosotros mentioned in the article introduction to loops.

If you would similar to test the code in the example in an online compile, click the button below.

Example ii: While loop to compare two numbers

In this case we are going to:

  • Take ii numbers, one large that nosotros proper noun large, and one smaller, that we call pocket-size. Both numbers are randomly selected to illustrate the example
  • Apply a while loop to print the value of both numbers equally long as the large number is larger than the small number.
  • For each iteration in the while loop, we will split up the large number by two, and besides multiply the smaller number past 2.
public static void main(Cord[] args) {     int large = 2345;     int small = 3;      while (large > small){         System.out.println("Large = " + big + " and " + "Modest = " + small);         big = big / 2;         small = modest * 2;    } }

The answer in this example will exist

Large = 2345 and Small = two Big = 1172 and Small-scale = 4 Big = 586 and Pocket-sized = 8 Large = 293 and Minor = 16 Big = 146 and Minor = 32 Big = 73 and Small = 64

Example iii: While loop using a random number

Permit's take a look at a 3rd and final example. In this example, we will use the random class to generate a random number. If yous do not remember how to employ the random class to generate random numbers in Coffee, you tin read more than about it here.

What we desire our programme to do is:

  • Generate a random number between 0 – 15.
  • While that number is not equal to 12, the currently generated random number should be printed, as well as how far the current number is from 12 in absolute numbers.
  • Finally, one time nosotros have reached the number 12, the program should end by printing out how many iterations information technology took to accomplish the target value of 12.
// Import the Scanner form import coffee.util.Random;  public class exempel {         public static void main(String[] args) {              // Creates a scanner object             Random rand = new Random();              // Creates a random integer             int randomNum =rand.nextInt(15);                          // Variable for number of iterations             int count = 0;                          // As long every bit the random number is not equal to 12             while(randomNum != 12){                                  Arrangement.out.println("Number is: " + randomNum +                 ", that is: " + Math.abs(12 - randomNum) + " from target value");                                  // Update the random number                 randomNum = rand.nextInt(15);                                  // Increase the counter variable by one                 count ++;              }                          // Print number of iterations              System.out.println("Target value reached in: " + count + " iterations");         } }

Furthermore, in this case, it volition not be easy to print out what the answer will exist since we get dissimilar answers every time. But it might look something like:

Number is: five, that is: 7 from target value Number is: 4, that is: eight from target value Number is: 4, that is: 8 from target value Number is: 7, that is: 5 from target value Number is: viii, that is: 4 from target value  Target value reached in: vi iterations

Why use a while loop in Java?

The while loop in Java used to iterate over a code block as long as the condition is true. We usually use the while loop when we do non know in accelerate how many times should be repeated. Furthermore, a while loop will continue until a predetermined scenario occurs. It can happen immediately, or it tin can crave a hundred iterations. Then the number of loops is governed by a result, not a number. For example, you can continue the loop until the user of the programme presses the Z key, and the loop will run until that happens.

Common errors when using the while loop in Java

  • Outset of all, you stop up in an infinity loop, due to several reasons, but could, for example, be that you forget to update the variables that are in the loop. Note that your compiler will end the loop, only it will also cause your program to crash/shut down, and you volition receive an error message.
  • You forget to declare a variable used in terms of the while loop. Remember that the get-go time the condition is checked is before yous outset running the loop torso.
  • Incorrect with ane in the number of iterations, unremarkably due to a mismatch between the state of the while loop and the initialization of the variables used in the condition. A good idea for longer loops and more all-encompassing programs is to test the loop on a smaller calibration before.

That was just a couple of mutual mistakes, there are of class more mistakes yous can make

Summary: While loop in Java

A while loop in Java is a so-called condition loop. This means repeating a lawmaking sequence, over and over once more, until a condition is met. Instead of having to rewrite your code several times, we tin instead repeat a code block several times. If the number of iterations non is fixed, information technology'south recommended to use a while loop.

Syntax: While loop

while (condition) {                 // While loop lawmaking block }

FAQ: While loop in Java

What is the status of the while loop?

The expression that the loop volition evaluate. As long as that expression is fulfilled, the loop volition be executed. For example, it could be that a variable should be greater or less than a given value.

Can yous use the while loop fifty-fifty if you know the number of iterations?

Yes, of class. It is possible to set a status that the while loop must go through the code block a given number of times. But for that purpose, it is usually easier to use the for loop that nosotros volition see in the adjacent commodity.

Tin I use a while loop within another while loop?

Yep, it works fine. Just remember to keep in mind that loops can "get stuck" in an infinity loop so that you pay attention and then that your programme can move on from the loops.

hilllian1974.blogspot.com

Source: https://code-knowledge.com/java-while-loop/

0 Response to "Java How to Check a Condition Then Run Through a Loop Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel