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.
do..while
-loop, or use awhile
-loop and place a copy of the first call before the loop. – MrSmith42 Sep 27 '13 at 9:27