Question

I have a switch statement acting as a menu, in this I am trying to read the users input. Currently I am using variable=in.next(); and this works. However it will only read one word and at points the user may need to enter more, so I tried using variable=in.nextLine();, which compiles, but when I run the program, I select my choice from the menu, and it skips the reading in and return to the menu.

Any help would be appreciated, thanks :)

Was it helpful?

Solution

Just use:

name=in.nextLine();

and

String choice = in.nextLine();

This should be in the constructor, and at the top of runApp.

That way, you're not leaving the new line in the buffer (where it will be used for e.g. dp).

You should have:

dp=in.nextLine();

as described in your question.

OTHER TIPS

You either have to strip the newline character \n from the user input or assume it's there in your switch statement.

Pretty much because you decided to use nextLine() the user input to the computer will look like this

 f\n

So just compare the strings accordingly!

OK I think I am too inept at Java and have put my question badly.

When I take the users input it takes only 1 word, I want it to take everything they put basically, and when I use nextLine, this just skips the reading and takes me back to selecting a choice.

Switch selector can be only integer, short, char or enum. String cannot be used as a switch selector.

If I understood you correctly you would like to control your flow using words entered by user. If you have predefined list of words I'd suggest you to use enum:

enum Words { start, stop, beep, }

Now user enters a word beep. You can say:

Words command = Words.valueOf();
///
switch (command) {
    case start: /* start something */ break;
    case stop: /* stop something */ break;
    case beep: /* beep!!! */ break;
    default: throw new IllegalArgumentException("Unknown command " + command);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top