gpt4 book ai didi

java - 字典搜索超时……该怎么办

转载 作者:行者123 更新时间:2023-12-01 09:52:15 26 4
gpt4 key购买 nike

import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;

class Solution{
public static void main(String []argh){
Map<String,String> phoneBook =new HashMap<String,String>();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n; i++){
String name = in.next();
String phone = in.next();
phoneBook.put(name,phone);
}
System.out.println("now search");
while(in.hasNext()){
String s = in.next();
for(Map.Entry<String,String> e : phoneBook.entrySet() )
{
e.getKey();
if(name1==s)
{
System.out.println(e.getKey()+" : "+e.getValue());
}
else
{
System.out.println("Not found");
}
}
}
in.close();
*

}
}*

我想做的是在字典中输入一些值,然后搜索字典中是否存在特定字符串......它正在工作,但由于超时而被终止。还有更好的方法吗???

最佳答案

它是一个 HashMap ,因此您应该使用它的功能,而不是逐个迭代键。

尝试:

 while(in.hasNext()){
String s = in.next();

String value = phonebook.get(s);
if(value!=null)
{
System.out.println(s+" : "+value);
}
else
{
System.out.println("Not found");
}
}

关于java - 字典搜索超时……该怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37532103/

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