Ale*_*exM 0 java special-characters switch-statement
我试图使用Switch语句作为菜单界面,我想知道如何包含一个"帮助"选项,由用户输入'?'触发 符号.
但由于Switch正在接受'char'类型,我不确定这是怎么回事.
你能指点我正确的方向吗?
这是我到目前为止的非编译代码:
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; }
Run Code Online (Sandbox Code Playgroud)
另一个问题是,是否有更合适的方法来实现'退出'选项,而不是仅在输入'x'后休息?
感谢您抽出宝贵时间阅读我的问题.
Java语言中的问号字符没有什么特别之处.你不需要逃避它 - 它不像正则表达式.只需使用:
case '?': showHelp(); break;
Run Code Online (Sandbox Code Playgroud)
见JLS 3.10.4节为你的人物就一定要逃逸(和可用的转义序列).
编辑:根据评论,问题是该showHelp()方法,它构建一个字符串,但不返回它.你可能想要这样的东西:
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");
}
Run Code Online (Sandbox Code Playgroud)
...适合的价值out.
(顺便说一句,你的支撑风格很奇怪,而且我觉得很难读.在Java中有两种常见的支撑方式 - 我在上面的代码中展示的那种,以及"在同一条线上的支撑"缩进作为右括号"版本.为了其他可能阅读您的代码的人,可能值得采用其中一种常见的样式."