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

Can't receive user input within a switch statement

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

问题是当用户尝试输入时,我收到一条 'StringIndexOutOfBoundsException: String index out of range' 消息。这是代码:

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