how to write answerable questions into java??
sorry if the title wasnt clear.
i want to be able to write a question into the program which will respond differently depending on what is entered by the user.
ie. Do you want to continue?
then the user can then either enter yes or no.
then depending on what they enter diffent code starts.
what i have tried is this.
screen.println( "Would you like to continue?" );
answer = keyboard.readLine()
if (answer == yes)
{
Further code is entered here
}
if (answer == no)
{
screen.println("okay");
}
this was my general idea i am not sure if this can be fixed or is it completely wrong.
Any help is apperciated, and thank you in advance
Re: how to write answerable questions into java??
Never use == to compare string values. readLine returns a string I'm assuming. [Not sure what class 'keyboard' is, scanner uses nextLine]
Compare the answer to some predefined value using string comparison, EG
Code Java:
if(answer.toLowerCase().equals("yes"))
{
...
}
Please post the entire code, or an SSCCE [Short Self-Contained Complete Example] that demonstrates what you are attempting to do, however I will first point you to the
java tutorials.
Re: how to write answerable questions into java??
What is the screen object in your code:
Your general idea can work, except you won't want to use == to compare Strings since == tests to see if two String *objects* (or any objects for that matter) are one and the same. Rather you want to check if two Strings contain the same content -- the same letters and in the same order, and for that you should use the equals(...) or equalsIgnoreCase(...) methods. Also your String literals should be surrounded by "", and so you'll be checking to see if one Strings holds "yes" or "no":
Code :
// we'll use equalsIgnoreCase since we don't care
// if the user types in "yes" or "Yes" or "yeS"
if ("yes".equalsIgnoreCase(answer)) {
// do something
}
Note that I prefer the above code to this:
Code :
if (answer.equalsIgnoreCase("yes")) {
// do something
}
because with the former code, I reduce the chances of getting a NullPointerException in case answer is null.