Search code examples
javaswitch-statementspecial-characters

How to implement a special character(?) as an option in a Switch of type 'char'?


I am attempting to use a Switch statement to use as a menu interface, and I was wondering how I can include a "help" option, which is triggered by the user having input a '?' symbol.

But as the Switch is accepting type 'char', I am not sure how this is possible.

Could you please point me in the right direction?

Here is my non-compiling code so far:

private char readChoice()
{   System.out.print("Choice (a/b/c/s/?/x): ");
    return In.nextLine().toLowerCase().charAt(0); }

private void execute(char choice)
{   switch (choice)
    {   case 'a': routes.show(); break;
        case 'b': customers.book(routes); break;
        case 'c': customers.show(); break;
        case 's': routes.showSchedule(); break; 
        case '\?': showHelp(); break;
        case 'x': break;    }}

private String showHelp()
{   String helpText = "  A/a  Show bookings by route\n";
    helpText +=       "  B/b Book a trip\n";
    helpText +=       "  C/c Show bookings by customer\n";
    helpText +=       "  ? Show choices\n";
    helpText +=       "  X/x Exit\n";
    return helpText;    }

One other question, is there a more suitable way to implement the 'Exit' option, rather than just having a break after an 'x' is input?

Thank you for taking the time to read through my question.


Solution

  • There's nothing special about the question mark character within the Java language. You don't need to escape it - it's not like in a regular expression. Just use:

    case '?': showHelp(); break;
    

    See JLS section 3.10.4 for the characters you do need to escape (and the escape sequences available).

    EDIT: As per the comments, the problem is with the showHelp() method, which builds a string but doesn't return it. You probably want something like:

    private String showHelp() {
        out.println("  A/a  Show bookings by route");
        out.println("  B/b Book a trip");
        out.println("  C/c Show bookings by customer");
        out.println("  ? Show choices");
        out.println("  X/x Exit");
    }
    

    ... for a suitable value of out.

    (As an aside, your bracing style is odd and I for one find it pretty hard to read. There are two common bracing styles in Java - the one I showed in the above code, and the "brace on a separate line at the same indentation as the closing brace" version. For the sake of others who might read your code, it's probably worth adopting one of those common styles.)