I'm back!
We're learning Java WhileLoops today.
What Are "while" loops
Just like For Loops, While loops are another type of loops in Java, except they rely on only a true/false statement to determine whether they run or not.
Parts of a While Loop
A while loop has 3 parts:
- The starting statement (the while(stuff is/not true)) part
- The opening/closing brackets
- The statement(s) within the bracket
Create A While Loop
Assuming you have already fired up your favorite IDE and have an empty class created, write a class and add the main method.
Inside of the main method, lets make a While loop that loops until the number 5 is reached.
- Create your starting statement:
- Now create your statements. For our case, we want to check if our variable x is equal to "5". If it is lower than 5, we increment by 1
- Next we add an else statement so that if x is equal to 5, we print out the word "five". And finally, we close the while loop (if you haven't already, or if your IDE didn't close it already for you)
- Now run your program. The output should just say "five". This is because we never wrote any statements for it to print anything if x didn't equal 5.
Comparing: For vs. While loops
- Both will loop infinitely if you don't write them properly (such as if you wrote a statement that will always be true, both loops can loop infinitely, and you'd have to terminate the program (click that little red X in Eclipse in the output window)
- You'd use a for loop for when you wanted something repeated a certain number of times.
- You'd use a while loop for when you don't know how many times that a statement(s) should be repeated, or until something became false.
If you want a for loop to keep looping until the number "2" is reached, you can write:
for(int x = 0; x <= 2; x++){
if(x == 2){
System.out.println("two");
}
}
We can write that a while loop to output that same output by writing (with a While loop) :
int x = 0;
while(x <= 2){
if(x != 2){
x++;
}else{
System.out.println("two");
}
}
But the great thing about While loops is that the True/False statement doesn't always have to be a number. For example, if we wanted something to loop until a variable called "y" was false:
boolean y = true;
while(y == true){
if(1 > 2){//this is going to be false
y = false; //yes, you can change the value of a variable
}
}
Just updated your iPhone to iOS 18? You'll find a ton of hot new features for some of your most-used Apple apps. Dive in and see for yourself:
Be the First to Comment
Share Your Thoughts