While Loops
Subscribe to Tech with Tim
While Loops
In java we have something called a while loop. A while loop is very similar to a for loop in the sense that they both rely on a condition to be true to continue to run. Unlike for loops, while loops do not have a counter variable associated with them. The block of code inside the {} following the condition of a while loop will continue to run until the condition is false.
Here is the basic syntax for a while loop.
while(condition){ // do this }
We typically use a while loop when we are unsure about how many times we may be looping. An example of a situation where we would use a while loop is the following: We would like to continue asking the user to input a number until they type one within a certain range. You can see this implemented below.
boolean run = true; Scanner sc = new Scanner(System.in); while(run){ System.out.print("Please type a number between 1 and 10"); int input = sc.nextInt(); if (input > 0 && input < 10){ System.out.println("That number falls within the range!"); run = false; // Stop running the loop } else{ System.out.println("Try again..."); } } // This will continue to run until the number inputted is between 1 and 10
For Loops vs While Loops
We typically use for loops when we know the number of times to run the loop. That means we use while loops when the amount of times to loop is unknown.
However, It is worth noting that everything we do with a for loop can also be done with a while loop (see below).
for(int x = 0; x < 10; x++){ System.out.println(x); }
int x = 0; while(x < 10){ System.out.println(x); x++; }
Both blocks of code above are equivalent and print the same thing.