gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:54:38 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com