I’m a newbie at Java programming (only academic experience), and I am trying to create a text based game style program that has a yes no prompt at various sections in the program. How do I do this? I want to System.exit( 0 ) if == no, else continue with my choice menu if == yes. Help please?
It’s kinda hard to tell what you are asking, so I’ll just try to answer as much as possible with my little knowledge of Java.
To get user input, first you need to create an BufferedReader, probably with a line like this in the main class:
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
It’s static because you only need to create one for your program.
Then whenever you want to get input just go:
String input = stdin.readLine();
and you’ll get a String containing the text they type up until they press enter.
To see if they say “yes” or “no” exactly as typed, just do this:
if( input.equals( “yes” ) )
{
doStuff();
}
else if( input.equals( “no” ) )
{
doOtherStuff();
}
And replace those silly function names I wrote with your own code.
A way to make it easier on the player, though, would be to do something like this:
if( input.charAt(0) == ‘Y’ || input.charAt(0) == ‘y’ )
{
doStuff();
}
else if( input.charAt(0) == ‘N’ || input.charAt(0) == ‘n’ )
{
doOtherStuff();
}
That means that they really only have to type a ‘y’ or an ‘n’ and capitalization doesn’t matter. Even if they misspell it, as long as they got the first letter right, they’ll be fine.
I might’ve totally missed the point here, and maybe I gave you too much stupid information, but I’ve actually written this sort of thing in Java. Let me tell you, Java is not the language to write this sort of thing in. I know it was a hell of a lot easier to write this stuff in QBasic. I don’t know what’s a good text-adventure language these days, though.
If you want to write a text adventure game, you should take a look at Inform or TADS. They’re both designed specifically for this purpose.
Thanks for the links Jooles, I will definately look into those. As HoldenCaulfield suggested, you may have the easier way of going about it, but what I have now is using a standard JOptionPane to get input for the yes/no and then proceeding. Is there some way to just create a boolean yes/no that will handle this without the buffered reader? Or am I best off just using the buffered reader (which I was never comfortable with).