【发布时间】:2016-04-14 00:37:56
【问题描述】:
我有以下输入。
3
sam
99912222
tom
11122222
harry
12299933
sam
edward
harry
mark
john
这是我的代码
public static void main(String[] argh) {
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keyList, outputList = new LinkedList<String>();
Scanner in = new Scanner(System.in);
int N = in.nextInt();
for (int i = 0; i < N; i++) {
String name = in.next();
int phone = in.nextInt();
in.nextLine();
map.put(name, phone);
}
keyList = new ArrayList<String>(map.keySet());
String s = in.nextLine();
while (in.hasNext()) {
if (keyList.contains(s)) {
outputList.add(s + "=" + map.get(s));
} else {
outputList.add("Not found");
}
s = in.nextLine();
}
in.close();
for (int i = 0; i < outputList.size(); i++) {
System.out.println(outputList.get(i));
}
}
我的问题是我无法确定输入是否结束,因为while (in.hasNext()) { 在最后一次输入后冻结。最后一次输入后如何关闭扫描仪?
【问题讨论】:
-
你不能把
String s = in.nextLine();作为while的第一行吗? -
@cricket_007 即使在同样的事情发生后
-
你有一个无限循环,只有在标准输入结束时才会结束。但是标准输入永远不会结束。它不像一个只有固定行数的文件。它不断地期望用户输入一些东西。因此,您需要指示最终用户键入一些特殊字符串,您的代码会识别为输入的结尾,并在您读取该特殊字符串后停止循环。
-
hasNextLine怎么样? -
您应该定义一个“停止”输入值(例如,当给定输入 =“-1”时)break while
标签: java