【问题标题】:No Printed out Twice?否 打印两次?
【发布时间】: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


【解决方案1】:

您没有显示实例化 parent 映射的位置,或者您添加到其中的其他内容,但看起来您在其中添加了一个元素,其键不是“母亲”或“父亲”。如果是这样的话,那么:

  • if(pairs.getKey() == father &amp;&amp; pairs.getValue() == "sarah") 条件将评估为假,然后,
  • 在你的 else 块中,if(pairs.getKey() == father) 也将评估为 false,
  • System.out.println("No"); 行不在该条件范围内,因此无论如何评估第二个条件,只要第一个条件为假,就会打印“否”。

此外,正如 cmets 中所述,您应该使用 .equals() 来比较字符串 (if(pairs.getKey().equals(father))) 而不是 ==

【讨论】:

    【解决方案2】:
    if(pairs.getKey() == father){
                    System.out.println("F = " + pairs.getKey() + "\n" + "C = " +
                    pairs.getValue() + "\n" + "Yes");
                    }
    
                    System.out.println("No");
    

    大括号外的语句是当上面的第一个 if 语句为假时,您得到双否的原因。

    【讨论】:

      猜你喜欢
      • 2014-02-16
      • 1970-01-01
      • 2023-03-18
      • 2021-03-29
      • 2014-07-19
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多