While & Do While Loops

OliverE

Power member.
Reputation
0
While & Do While Loops
You will need 15 posts to view the code in this thread

While Loop
The while loop is another way of looping a snippet of code while something meets a criteria. For example, while lowOnStock is false then keep checking stock. Once the criteria is not met then we carry on with the rest of the code.

Below is a really basic example showing how while loops work.
  • Your first asked if you want to enter the loop.
  • Upon entering the loop your then asked if you want to stay in the loop.
  • Answering No to any of the questions will then carry on with the code.
Try it out for a better understanding of how it works.
Notice how we use code from the previous String Equality tutorial.

[hide=15][java]
import java.util.*;
public class whiledo {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String ans;

System.out.println("Do you want to go into the loop? [Yes/No]");
ans = sc.next();

while(ans.equalsIgnoreCase("Yes"))
{
System.out.println("Do you want to stay in the loop? [Yes/No]");
ans = sc.next();
}

System.out.print("Program Finished");
}
}
[/java]




Do While Loop
The do while loop is a way of looping a specific section of code depending on a criteria just like the while loop. The difference being is that in a while loop the code will only be executed if the criteria is met, if its not it will just skip it.
A Do While loop will always execute the loop code once and then it will check the criteria. An easy way to remember this is that in a do while loop, the 'while' comes after the do, so it does the code first then checks. In a while loop, the 'while' comes first meaning it checks before it does the code.

The example below is really basic and kind of pointless, but still shows how a do while works.
Notice how it asks for a value before it actually checks what the value is.

All this example does is;
  • Ask for a value
  • If the value is between 1 and 100 then finish the program
  • If the value is outside the criteria then loop the 'ask for value' code

[java]
import java.util.*;
public class dowhile {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int guess;

do
{
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("What do you think it is?");
guess = sc.nextInt();
} while((guess<1) || (guess>100)); //Process guess value

System.out.println("Program finished");
}
}
[/java][/hide]
Thats it for loops
Let me know if you have any questions
Thanks
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…