java - 无法在 switch 语句中接收用户输入

标签 java exception switch-statement user-input

我刚刚开始编写一个菜单,它要求用户选择他们想要执行的操作(如页面等)。一旦他们选择了操作,他们需要能够使用键盘输入来完成任务。

问题是,当用户尝试输入时,我收到“StringIndexOutOfBoundsException:字符串索引超出范围”消息。这是代码:

int choice;
  boolean finished= false;
  while (!finished) {
     System.out.println(currentUser.getFirstName() + ". Please choose: ");
     System.out.println("'l'- To like a page, 'e' to exit");
     choice = keyboard.nextLine().charAt(0);
     switch (choice) {
        case 'l':
           PageList.displayAllPages();
           System.out.println("Enter the page to add");
           int pIndex = keyboard.nextInt();
           currentUser.insertPage(PageList.findPage(pIndex).toString());
           break;
        case 'e':
           finished = true;
           currentUser.saveMyPages(userDir);
           currentUser.saveMyFriends();
           break;
        default:
           System.out.println("Invalid entry");
     }//switch
  }//while

显然问题是:

int pIndex = keyboard.nextInt();
currentUser.insertPage(PageList.findPage(pIndex).toString());

我该如何解决这个问题?我需要将其放在 try catch 语句中吗?

这是痕迹。第 79 行实际上是 switch 语句之前以 'choice = Keyboard' 开头的行

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:646) at B00670983.SocNetApp.main(SocNetApp.java:79) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

最佳答案

执行该行后

int pIndex = keyboard.nextInt();

在 while 循环的第二次迭代中,输入流中仍然有结束行字符,并且

choice = keyboard.nextLine().charAt(0);

结果为空字符串。 因此,在该行后面再添加一个 keyboard.nextLine();

int pIndex = keyboard.nextInt();

参见related question

关于java - 无法在 switch 语句中接收用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909907/

相关文章:

java - java中输出字数统计时出错

java - 简易计算器不打印答案?

java - System.nanoTime() 是否保证返回唯一值?

java - BugSense 崩溃了

java - 为什么添加 try block 会使程序更快?

java - 如何用Java处理来自客户端的Websocket消息?

javascript - Switch 语句和类

java - 多模块maven项目: Failed to execute goal on project,无法解析项目的依赖关系,无法找到 Artifact

c# - .NET 4.0 中网络共享的异常保存配置

java - java switch case 语句是否为负 int 值执行多个 case?