【发布时间】:2017-06-25 13:13:09
【问题描述】:
此代码试图从用户那里接受密钥并将它们存储到字符串数据数组中。稍后在程序中,每个键的值以某种特定格式显示。
首先,我希望这个循环在用户输入为空/下一行时结束/退出。我不想使用任何 EOF 字符或字符串退出循环。
我对以前的 SO 问题/解决方案进行了一些搜索,但在我的情况下不起作用。需要帮助解决这个问题或任何其他替代方案是最受欢迎的。
提前致谢!
class DictionaryAndMap{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
Map<String, Integer> mp = new HashMap<String, Integer>();
String name;
int phone;
for(int i=0; i<len; i++){
name = sc.next();
phone = sc.nextInt();
mp.put(name, phone);
}
int i=0;
String arr1[] = new String[10];
String nam;
// I couldn't exit out of this loop
while(sc.hasNext()){
nam = sc.next();
if(nam!=null && !nam.trim().isEmpty()){
arr1[i] = nam;
i++;
}
else{
break;
}
}
// iterating through the array to find the search inputs
for(String j: arr1){
if(mp.containsKey(arr1[j])){
System.out.println(j+"="+mp.get(j));
}else{
System.out.println("Not found");
}
}
}
}
P.S. 即使输入为空/null/" ",hasNext() 值也不会更改为 false,因此 while 循环永远不会结束。我怎样才能让 hasNext() 检测到任何这些空输入数据,因此它可以退出循环?
【问题讨论】:
-
else if声明是多余的。只要第一个if是false,它就永远是true。 -
我确实遇到了那个线程,但是除了使用 EOF 语句之外没有其他解决方案吗?有没有办法至少我可以从用户输入或类似的东西中跟踪 \n?
-
@Akhil 使用
hasNext()here 可能会有帮助。 -
^ 这几乎指出了我的问题...也许我应该尝试不同的方法:)
标签: java loops collections hashmap iteration