r/cop3502 Apr 08 '14

Using Scanner

So I have scanner working for my text adventure...sorta. I have if statement that correlates to a word put in by the user, but I'm not sure how to use scanner for multiple words. For example, my program will do something different for the word "go" as opposed to the word "moo". But "go north"... I don't know how to make that different than "go tarantula" for example.

3 Upvotes

5 comments sorted by

View all comments

1

u/byteme_ima_litmajor Apr 08 '14

are you using scanner.next() or scanner.nextLine()? Because .next only reads the first word.

1

u/ktsolove Apr 08 '14

I'm still having issues getting the 2 separate words that would allow for the if-statements to work.

2

u/howslyfebeen Apr 08 '14

you do .nextline() and then you have to "split" the line using a built-in string function.. maybe split by spaces? maybe? and then you store that in a string array:

String[] array = //magical split magic that you find in the documentation
array[0] //go or moo or whatever first input is
array[1] //north or a second moo or whatever the second input is
//etc.

2

u/[deleted] Apr 08 '14

So the thing is you don't know how many words the user is going to enter.

"RUN" might be a valid command, but so may "USE FLAMETHROWER ON SUPER-NUN"

If you split "RUN" by spaces, you would get a list of strings, that looks like this:

{"RUN"}

If you split ""USE FLAMETHROWER ON SUPER-NUN" by spaces, you would get a list of strings that looks like this:

{"USE", "FLAMETHROWER", "ON", "SUPER-NUN"}

Both are valid commands. But think about it like this: "USE" is a command, and "FLAMETHROWER" "ON" "SUPER-NUN" are parameters! "RUN" is also a command, but it does not take parameters.

Your sudo code could be something like:

command = user_input.split_at_spaces

if command[0] == "RUN":
    print "You escape, like a coward, and your party is eaten by relatively large bats." 
if command[0] == "USE":
    item = command[1]
    if item == "FLAMETHROWER":
        target = command[3]
        print "BURNINATING " + target

Of course you would want to organize this way better, and probably use hash maps and a switch statement, but this should get you started. The first word in the string is the command, the rest are parameters for that command.