【问题标题】:looping Nested If else in a TreeMap logic在 TreeMap 逻辑中循环嵌套 If else
【发布时间】:2015-06-26 11:01:01
【问题描述】:

我将值放入TreeMap 中,如下所示:

  if (hdr.getName().equalsIgnoreCase("Ip4")) {
     map.put(1, f);
 } else if (hdr.getName().equalsIgnoreCase("ethernet")) {
     map.put(2, f);
 } else if (hdr.getName().equalsIgnoreCase("tcp")) {
     map.put(3, f);
 } else
 if (hdr.getName().equalsIgnoreCase("udp")) {
     map.put(4, f);
 }

我正在尝试使用以下方法检索它:

Iterator < Map.Entry < Integer, Field >> entries = map2.entrySet().iterator();
while (entries.hasNext()) {

    Map.Entry < Integer, Field > entry = entries.next();

    if ((entry.getKey() == 1)) {

    stringBuilder.append(entry.getValue().getSource());
    stringBuilder.append(",");
    stringBuilder.append(entry.getValue().getDestination());
    } else if ((entry.getKey() == 2)) {

    stringBuilder.append(entry.getValue().getSource());
    stringBuilder.append(",");
    stringBuilder.append(entry.getValue().getDestination());
    } else if ((entry.getKey() == 3)) {

    stringBuilder.append(entry.getValue().getSource());
    stringBuilder.append(",");
    stringBuilder.append(entry.getValue().getDestination());
    } else if ((entry.getKey() == 4)) {

    stringBuilder.append(entry.getValue().getSource());
    stringBuilder.append(",");
    stringBuilder.append(entry.getValue().getDestination());
    }

}

现在,我想要的输出是,如果没有找到任何键,它应该放在 else 部分(我没有包括在这里,因为我没有得到所需的输出)并且它应该附加

               stringBuilder.append(,,);

例如

        If key 1 contains 12,13
        If key 2 is not present ,,
        If key 3 contains 10,11
        If key 4 contains 14,15

所以想要的输出应该是

       12,13,,10,11,14,15

请在我对此感到头疼时帮助我解决逻辑问题。

谢谢

【问题讨论】:

  • 您正在遍历该地图中存在的条目,因此如果地图中没有 2,则不会为它打印任何内容。
  • 你不能有一些从 1 到 4 循环的变量,然后使用 get 来查看地图中的内容吗?
  • @Eran ,如果 2 不存在,我希望 (,,) 被打印,而且它在任何时候 1 , 2 ,3 , 4 或它的任何组合都不会出现,所以我必须检查值是否存在任何键。
  • 大卫,我会检查并更新

标签: java loops if-statement treemap


【解决方案1】:

感谢大卫的提示,我用解决了它

    for (int i=1 ; i<=map2.size()+1; i++){
        if(map2.containsKey(i))
        {
            //appendString(map2.get(i));    

            stringBuilder.append(map2.get(i).getSource());
            stringBuilder.append(",");
            stringBuilder.append(map2.get(i).getDestination());

        }
        else{
            stringBuilder.append(",,");
        }

    }

【讨论】:

  • 我建议你测试 3 和 4 存在但 1 和 2 不存在的情况。你可能不会得到你期望的结果。
猜你喜欢
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多