hi,
the book always have code like this for the beginner ..

String status="yes"
do{

......
}while(status.equalsIgnoreCase("yes"));

what if the user enter y? or mistype "yes" to "yse"? the program crash... we can of course use if and else if and else or the switch statement's "default" to output the error message..

however, i am interested to know if there is a fancy way to do it with the do while loop.

Recommended Answers

All 9 Replies

The program wont crash, but as long as you don't type YES,Yes,yES etc. you will stay in the do...while loop.

Because you ask for a fancy way, I give it to you. So suppose you want to allow multiple answers without much work you can do this :

Scanner input = new Scanner();
String response = "";
System.out.println("Do you want to continue ?" Yes/Y/No/N);
response = input.nextLine();
do{
// Whatever you want to do
}while(response.toLowerCase().indexOf("y") != -1)

Now your program won't stop for any answer like Yes, yes, Y, y, Yeah, Yep, Why not, and also for ones you say yse,sey,eys,esy (mispellings) - Howzzat ?

Okay that was certainly a funny way of implementing it, only becuase you asked for, but on a more serious note, you should put the conditions, for which you want to allow the user to move ahead, in an OR clause, such as this :

while(response.equalsIgnoreCase("Y") || response.equalsIgnoreCase("Yes"))

You would ask here - what about the mispelled responses ? - Well in that case tell the user about the valid inputs. Ask him once more what he intends to do, may be he will not do the mistake again. The point here is to make sure that the user knows what he is doing.
To prove this point let's take the above example. Say that you have prompted the user with "Do you want to continue ?" in the above case and are waiting for his response. The user types, say, "Not yet" which certainly means he is not ready for giving you an input at this very moment, but the loop demostrated earlier will continue much to the user's surprise. This certainly shouldn't have been the case. Should it be? But you never imagined such a possibility and probably many others. This is a basic question, it certainly would not do much damage here (the user can certailny keep your program waiting for the input as long as he wants.) but this question points to a far more important programming/design decision. The option of allowing mispellings of 'yes' here direct towards an approach that brings flexibility in your program. Flexibility allows programs to run sometimes even under not the exactly appropriate conditions and this is where it leads to compromising the robustness of your system. To detail on this, let's see why flexibility causes our program to fail in the above case. In the above mentioned example, your program ASSUMES that because a lot of answers starting from character 'y' like Yeah, Yes, Yep - point in the positive intent of moving forward and because an answer containing the character 'y' might be a mispelling of 'yes', the user actually is wanting us to continue. But this assumption is what makes your program fail. Many times it is very important to make the user aware of what he is providing as an input as also it is important to make sure that the option you are assuming is actually the option opted by the user. For this it would be a good idea to restrict your set of positive answers to the most common 'Yes' or 'Y' and let the user type again for mispellings etc.

The reason I stress this point here is, many times during programming you would be faced with the dilemma of either making your program flexible or robust. This is a trade-off basically the more you would want to make your program/system flexible the less robust it would be and vice versa. Yes, we would all love programs to be 100% flexible and at the same time 100% robust, we would love to write and even more to use a program that exactly knows when the user wanted to type 'yes' and worngly typed 'yse' instead and when the user wants to say 'Not Yet'. Such a program would have to read the user's mind almost accurately, but we know such programs cannot be created as of now and till then it is always robustness that will win over flexibility because when a program deletes an important file when the user mistakenly clicked 'yes', the user would almost always think in his mind that the program would have better confirmed it with him rather than assuming his mistaken click as yes.

commented: Wow! Impressive speech :P +2

You could use the Logical (if I am correct) Operators ( AND (&&), OR (||) ) to achieve that. For example :-

while(status.equalsIgnoreCase("yes") || status.equalsIgnoreCase("yse")  || ..)

<EDIT>
Three posts in a minute on the same thread, thats the first time I have seen it.

One thing to note on the do-while loop verruckt24 posted above:
You probably want a normal while() loop there instead of the do-while(), otherwise you're performing the loop code before checking the user's response.

thanks everyone.

however, what i really was asking is if there is a way to make sure the user answer the way i want them to answer and otherwise pop an error message.

basically i am asking to transfer this

if(answer =="yes")
{
 continue;
}

else if (answer =="no")
{
   exit
}

else
{
    output error
}

to a do while loop or while loop

you could do something like this but not sure its what you are looking for...

String input;
		Scanner s = new Scanner(System.in);

		do 
		{
			System.out.print("Would you like to continue (yes or no): ");
			input = s.nextLine();
			
			while(!input.equals("yes") && !input.equals("no"))
			{
				System.out.println("Error: Invalid input!");
				System.out.print("Enter yes or no: ");
				input = s.nextLine();
			} 

		} while(input.equals("yes"));

You have 2 while loops one inside the other that do exactly the same thing in the opposite. There are much better codes than that:

boolean done = false;
while (!done) {

// and now k2k's code

enter input

    if (answer.equals("yes"))
    {
        do whatever calculations you want to do
    }
    else if (answer.equals("no"))
    {
        done=true;
    }
    else
    {
        System.out.println("Invalid option");
    }
}

thanks all, i think there are really many ways doing it.

What is wrong with the following :
Do you want to continue, stop...(whatever)?
(Type y for "yes" and n for "no".)

Don't annoy users, by asking them to type 3 letters, and when one key is mistyped show them an error message. Users don't like that.
One key or click of the mouse to get something done from a user is more than sufficient and also easier to program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.