gpt4 book ai didi

Java 为什么扫描仪不能在交换机内工作

转载 作者:行者123 更新时间:2023-12-01 23:29:55 25 4
gpt4 key购买 nike

我有一台扫描仪,要求提供一些首选项。它创建一个介于 0 和 3 之间的 int 变量 choice。然后我执行以下操作:

String location;
switch(choice){
case 0:
System.out.println("Please type the zip codes you would like to search in a comma separated list");
location = input.nextLine();
break;
case 1:
System.out.println("Please type the street names you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
case 2:
System.out.println("Please type the boroughs you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
default:
location = "none";
break;
}
String locations[] = location.split("\\s*,\\s*");

现在对我来说这似乎完全没问题,但是当 choice 设置为 0,1 或 2 时,它将打印正确的行,但跳过用户必须输入某些内容的部分(看起来像 location=. ..)

这意味着它不会让用户有机会输入任何内容,因此 locations 变成空白列表。 为什么会发生这种情况以及如何解决它?

最佳答案

您可能正在读取最后一个输入后的换行符,而不是真正的下一行。尝试:

int choice = input.nextInt();

input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
case 0:
Syst...

提示选择的 nextInt() 调用不会结束该行。因此,在 nextInt() 之后第一次调用 nextLine() 将返回一个空字符串。要解决这个问题,请吃掉整数后面的空行,然后继续。

关于Java 为什么扫描仪不能在交换机内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482877/

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