-1

I need help with switch, here is my part of my code that I need help with.

Scanner kb = new Scanner(System.in);
do
    {
        System.out.println("\nAt each turn, type: ");
        System.out.println("P to print");
        System.out.println("M to mix (shuffle the cards)");
        System.out.println("S to save");
        System.out.println("Q to quit");
        System.out.println("Just ENTER to play a turn");

        meun = kb.nextLine();


        switch (meun)
        {
            case ("P"):
            case ("p"):     System.out.println("\nPlayer1 cards: " + p1.toString());
//More Codes...
            case (//Would like to have an ENTER here.):

How do I just get an "enter" in the next case after P. What I want is that if the user just hit enter then the program will play another turn. I was thinking about doing String.valueOf(kb.nextLine()) but that does not work.

Thank you for your help.

Paincakes
  • 137
  • 1
  • 2
  • 11

3 Answers3

4

In your case, you should check for en empty string since, Just enter will actually return an empty string to Scanner.nextLine().

    switch (meun)
    {
    case "":
         // Next turn.
    }
Codebender
  • 14,221
  • 7
  • 48
  • 85
2

Just use an empty string, like:

case "" : System.out.println("Blah, blah, blah...");

Or change "" to KeyCodes.KEY_ENTER or just 13 should work. And change the input from a String to a char.

goncalopinto
  • 433
  • 2
  • 8
1

For console input, hitting enter sends your command to standard input and is also not a character that you could put in a switch. For your situation it's probably easiest to use another character like t to play a turn.

If you were to implement a key listener it would be possible to detect the enter key as an input, but that seems like it would be overkill for your program's needs.

EDIT: the other answerers have helpfully provided much more useful answers!

ahe
  • 227
  • 1
  • 7
  • I wish that were the case. But for this program, my professor wants us to implement an enter key. – Paincakes Mar 04 '16 at 02:53
  • Perhaps try [this](http://stackoverflow.com/questions/18281543/java-using-scanner-enter-key-pressed). – ahe Mar 04 '16 at 02:54