英文:
Unable to retrieve the values added in the hashmap
问题
这段代码在我尝试第二次检索数据时没有给我数据。
- 我输入域名和IP地址
- 然后我再次输入DN和Ip
- 我搜索第一个IP,它给出了正确的结果。
- 当我搜索第二个IP时,它说找不到域名。
我不确定为什么我的循环没有给出正确的结果?
我可以看到数据是可用的,它进入了if部分并进行了验证,但没有返回数据,它转到else部分并打印出没有可用数据。
//主类
{
System.out.println("1. 添加DNS详细信息");
System.out.println("2. 查找匹配的域名");
System.out.println("3. 退出");
System.out.println("请输入您的选择");
//输入选择后
System.out.println("请输入IP地址以查找域名");
ip = sc.nextLine();
DomainName = dBO.findDomainName(ip);
}
//FindDomainname.java类
public String findDomainName(String ipAddress) {
String domain=null;
if(domainMap.isEmpty()){
return domain;
}
else
for (Map.Entry<String, String> entry : domainMap.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (ipAddress.equals(v)) {
domain = k;
}
else
{
domain = "找不到匹配的域名";
}
}
return domain;
}
英文:
This code is not giving me data when i try to retrieve data second time.
- I enter domain name and ip address
- again i enter DN and Ip
- I search for 1st ip its gives correct result.
- When i search for 2nd ip it says domain name not found
I am not sure why my loop is not giving correct result?
I can see that the data is available it enters the if section verified but does not return the data,it goes to the the else section and prints that no data is available.
//Main class
{
System.out.println("1. Add DNS details");
System.out.println("2. Find matching Domain Name");
System.out.println("3. Exit");
System.out.println("Enter your choice");
//After entering the choice
System.out.println("Enter the IP address to find the domain name");
ip = sc.nextLine();
DomainName = dBO.findDomainName(ip);
}
//FindDomainname.java class
public String findDomainName(String ipAddress) {
String domain=null;
if(domainMap.isEmpty()){
return domain;
}
else
for (Map.Entry<String, String> entry : domainMap.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (ipAddress.equals(v)) {
domain = k;
}
else
{
domain = "No matching domain name found";
}
}
return domain;
}
答案1
得分: 1
你需要在找到该条目时立即跳出for循环,否则它会继续遍历地图中的下一个条目,而该条目可能不匹配。像这样添加break语句:
if (ipAddress.equals(v)) {
domain = k;
break;
}
英文:
You need to break out of the for loop as soon as you find the entry, otherwise it will move on the the next entry in the map and that entry may not match. add break statement like so:
if (ipAddress.equals(v)) {
domain = k;
break;
}
答案2
得分: 1
以下是代码的中文翻译:
一个流式解决方案。您的错误是在找到匹配项时没有跳出循环。
public String findDomainName(String ipAddress) {
return domainMap.entrySet().stream()
.filter(entry -> entry.getValue().equals(ipAddress))
.findAny().orElse(domainMap.isEmpty() ? null
: "找不到匹配的域名");
}
英文:
A Stream solution. Your error was not breaking out of the loop when a match was found.
public String findDomainName(String ipAddress) {
return domainMap.entrySet().stream()
.filter(entry -> entry.getValue().equals(ipAddress))
.findAny().orElse(domainMap.isEmpty() ? null
: "No matching domain name found");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论