While loops in Java
dev-aspires
Posted on April 9, 2022
Incase you missed my last tutorial on Java for loops, you can click the link below.Java For Loops In the last tutorial I explained in details, the concept of for loops in Java, and how to use it in your programs. However, in this tutorial I will be explaining the concept of while loop in Java, the syntax of while loop and how to use a while loop to iterate through an array.
The concept of a while loop
While loop is among the types of loops associated with Java, and it's been regarded as the most basic type of loop in Java, and therefore, can be utilize for several purposes within your program. Just like the for loop, a while loop can be used to perform some operations on the basis of a condition. In while loop, a counter is not always included. The number of iteration of a while loop depends on how often the while loop condition returns true
.
Initialization in while loop, most times can be optional, unlike for loop. Sometimes a while loop doesn't always execute in a cycle.
Take for example
System.out.println("You Input a wrong number");
int i = input.nextInt();
while(i==1||i==2||i==3||i==4){
System.out.println("inside the while loop block");
}
//if the user chooses any number different from 1,2,3 and 4.
System.out.println("outside the while loop block")
The above code uses a while loop to validate a user input, on the basis of some conditions, this while loop therefore iterates only once.
Syntax of a while loop
while(condition){
//Statements
}
The while loop condition accept an argument that returns a boolean value true
or false
, if true
the code within the while loop execute, but if false
the while loop terminates.
The flow of every while loop
The while loop has an accepted flow: initialization>condition>statements execution
The first stage is the initialization stage, it is regarded as the first stage of a while loop, this could be done by declaring a variable and initializing it as well.
The second stage is the condition stage, this stage must either return a true
value, or false
value. If it returns true
, the Statement in the while loop execute, but if it returns false
, the while loop terminates.
Using while loop as a counter
Just like a for loop, a while loop can also be used as a counter. The below program uses a while loop to iterate through from, 2 - 20, to print out even numbers.
int j = 2;
while(j <=20){
System.out.println(j);
j+=2;
}
In the above program, j is initialize to 2, the condition is checked if j is less than or equals to 20, if it returns true, the statement execute, but if it returns false the while loop terminates.
If you look closely, the statement enclosed in the while loop has an incrementor, which is used to increment the value of i to avoid an infinite loop.
While loop can be used to iterate through an array
int[] age = {20, 30, 40, 40, 90};
int i = 0;
while (i < age.length)
{
System.out.println(age[i]);
i++;
}
In the above code, we have an array of age, the while loop is used to iterate through the array and print out each elements in the array. The age.length
is use to check the total number of elements in the array, in the above program i
serves as an index.
Break statement in while loop
A break statement can also be used in while loop, just like a for loop:
int i = 1;
while (true)
{
System.out.println(i);
if (i == 20)
{
break;
}
i++;
}
In the above program a break statement was used to stop the program from been infinite. while(true)
means the program will forever return true.
While loop can be used to validate a user input
System.out.println("Select an option\n"+
"1.Add Users\n"+
"2.Delele Users");
int x = input.nextInt();
while(x==1||x==2){
//Do something
}
System.out.println("You Input a wrong number");
In the above program a while loop is used to validate the user input, and to ensure that the user chooses either 1 or 2, if the user choose a different number this statement System.out.println("You Input a wrong number");
execute.
Condition statement with while loop
int i = 0;
while(i<10){
i++;
if(i==5){
continue;
} System.out.println(i);
}
A condition statement can also be used in a while loop, to skip a particular iteration. In the above program an if statement is used to check if i==5
, it it returns true
then that particular iterate will be skipped.
While loop project
In the last for loop tutorial we built a guessing game using for loop, However, in this tutorial, we will be building the same guessing game using a while loop.
import java.util.*;
public class Main
{
static Scanner input = new Scanner(System.in);
static boolean hasWon;
static int count;
static int guess;
public static void main (String[] args)
{
System.out.println("Welcome to guess world");
System.out.println("Do you want to start the game? ");
System.out.println("1.Yes\n" +
"2.No");
int option= input.nextInt();
int guessNumber = (int) Math.floor(Math.random() * 10 + 1);
if (!( option == 2 ))
{
System.out.println("Welcome, choose a guess between 1 and 10\n" +
"you have only ten trials");
while (count <= 10)
{
int userGuess = input.nextInt();
if (userGuess == guessNumber)
{
hasWon = true;
System.out.println("Congratulation, you guessed right at " + count + " count");
count++;
break;
}
else if (userGuess < guessNumber)
{
hasWon = false;
System.out.println("Oops, you guessed a lower number, try an higher one");
count++;
}
else if (userGuess > guessNumber)
{
System.out.println("Oops, you guessed an high number, try an lower one");
hasWon = false;
}
}
if (hasWon == false)
{
System.out.println("You trials exceeds 10");
}
}
}
}
In the above program, we are building a guessing game using while loop, the player has only 10 trials, once the the number of times he had played the game exceeds 10, the game terminate, but if the player guessed right, a congratulations message will be shown on the console.
Conclusion
While loop, while powerful, can be easy to learn, it is the second most used java loops, and can be used for several purposes. However, in this tutorial I have explained the concept of Java while loops with some 'get to do' examples.
Posted on April 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.