Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

When I use a do-while loop, I can create a variable userInput, but don't need to initialize it until the do-while loop because it is not used until then.

import java.io.*;

public class Bla
{
    public static void main(String[] args) throws IOException
    {

        BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));

        String userInput; 

        do
        {
            System.out.print("Do stuff");
            userInput = stdin.readLine();
            if (userInput.equalsIgnoreCase("D"))
            {
                //Do stuff
            }
         }
        while (!userInput.equalsIgnoreCase("x"));
    }
}

When I use a while loop, I need to initialize the variable before it because I am using it immediately in the loop.

String userInput = null; 

while (!userInput.equalsIgnoreCase("x")); //<----Edit  this ";" was a copy and paste error, when posting the question
{
    System.out.print("Do stuff");
    userInput = stdin.readLine();
    if (userInput.equalsIgnoreCase("D"))
    {
        //Do stuff
    }
}

I don't want to initialize it as userInput = stdin.readLine(); before the loop, as I only want to type System.out.print("Do stuff");.

What are the pros and cons of using a do over a while? What other basics am I missing here? I am new to Java and want to have a base of good coding practice to build upon.

share|improve this question
    
There are no pros / cons. You must decide, if you need/want the check at the beginning(=> loop may never be executed) of the loop or at the end(=> loop will at least be executed once) of the loop. –  MrSmith42 Sep 27 '13 at 8:55
    
@MrSmith42 in this case, the loop MUST execute at least once –  user29649 Sep 27 '13 at 9:19
    
Than either use a do..while-loop, or use a while-loop and place a copy of the first call before the loop. –  MrSmith42 Sep 27 '13 at 9:27
    
@MrSmith42 yes, that was my point, it is replicating data.. so wouldn't it be better just to use a do? –  user29649 Sep 27 '13 at 9:31
    
my question comes from this post codereview.stackexchange.com/questions/31666/… –  user29649 Sep 27 '13 at 9:32

2 Answers 2

up vote 2 down vote accepted

The difference between the loops is only when they check the condition. As the do ... while loop checks the condition at the end of the loop, it will always run the code inside the loop at least once. So, a while loop fits better when you want to be able to skip the code inside the loop entirely.

In this case you want to run the code inside the loop at least once, so a do ... while loop is a better fit. Unless you do the user input inside the condition, then a while loop is a better fit:

while (!(userInput = stdin.readLine()).equalsIgnoreCase("x")) {
  ...
}

Often there is no best fit, because you have to do some extra checking whichever loop you use. Then you just have to choose which way of writing the code is easier to follow.


Note: There shouldn't be a semiconon after the where condition, that would detacht he code block from the loop. It's

while (...) {
  ...
}

not:

while (...); {
  ...
}
share|improve this answer
    
ty this line while (!(userInput = stdin.readLine()).equalsIgnoreCase("x")) was what I was trying to work out.. and the semi colon was a typo in copying and pasting.. will edit.. ty No won't edit, cos then yr answer will not make sense –  user29649 Sep 27 '13 at 15:07
    
@ThinksALot: Yes, I thought that it ought to be a typo, but I thought that I should mention it because it's such an error that is hard to spot. –  Guffa Sep 27 '13 at 16:02
    
@gufa of course u should mention it! :) it was because it was at the end of the do while and I copied and pasted it to the top for my question ;) thnx for yr answer, I appreciate people giving their time hey –  user29649 Sep 27 '13 at 16:18

There are no "pros" and "cons" of different loops, there's only "right" and "wrong".

Using the right loop is, arguably, arguably. The coder needs to decide what is the correct loop to use, let's look at some basic examples.

Whenever you iterate over a collection and want to process one item at a time, you use a for each loop:

for (Item item : items) {
    // Do something with item here.
}

If you want to touch multiple items at a time, or you need to know the index of each item, a simple for loop is what you're looking for:

for (int idx = 0; idx < items.length; idx++) {
    Item item = items[idx]; // For convenience.
    // Now you can use item and idx here.
}

If you have an operation which should run while a certain condition is true, you use a while loop:

while (condition) {
    // Do something here
}

And if you have an operation which should run at least once and as long as a condition is true, you use a do loop:

do {
    // Executed at least once
} while (condition)

Deciding which loop to use must come as natural to you as deciding if it should be a double or single, or integer or single. It is completely dependent on what you want to achieve and how.

share|improve this answer
    
thank you Bobby +1 comprehensive and useful answer well put. –  user29649 Sep 27 '13 at 15:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.