【发布时间】:2014-06-06 19:59:53
【问题描述】:
我有以下程序,它可能比它需要的复杂得多,但它是一个 Prolog 程序的镜像。我得到正确的输出,即
没有 X = 基安 是的 F = [大卫] C = 基安 是的 没有
除了最后一个不,我知道它与 if(pairs.getKey() == Father conditonal 和 while(it.hasNext()) 的循环有关,我只是不知道它为什么会打印出来没有两次,我该如何解决?是因为我两次调用pairs.getKey() ==父亲吗?
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class family {
public static void main(String [] args) {
family obj = new family();
obj.family();
}
public static int family(){
String[] male = new String[100];
String[] female = new String[100];
male[0] = "david";
male[1] = "kian";
female[0] = "anna";
female[1] = "sarah";
List<String> father = new ArrayList<String>();
father.add("david");
List<String> mother = new ArrayList<String>();
mother.add("sarah");
parent.put(mother, "kian");
parent.put(father, "kian");
Iterator it = parent.entrySet().iterator();
while(it.hasNext()){
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey() == father && pairs.getValue() == "sarah"){
System.out.println("Yes");
}else{
if(pairs.getKey() == father){
System.out.println("F = " + pairs.getKey() + "\n" + "C = " +
pairs.getValue() + "\n" + "Yes");
}
System.out.println("No");
}
if(pairs.getKey() == mother){
System.out.println("X = " +
pairs.getValue() + "\n" + "Yes");
}
it.remove();
}
return 0;
}
}
【问题讨论】:
-
不要将
==用于String相等,而应使用equals()
标签: java io iterator hashmap println