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

时间:2015-03-07 00:24:00

标签: java exception switch-statement user-input

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

问题是当用户尝试输入时,我收到'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'的行
  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0       at java.lang.String.charAt(String.java:646)       在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)       在java.lang.reflect.Method.invoke(Method.java:483)       在com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

1 个答案:

答案 0 :(得分:2)

执行行

int pIndex = keyboard.nextInt();

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

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

导致空字符串。 因此,在行

之后再添加一个keyboard.nextLine();
int pIndex = keyboard.nextInt();

参见related question