在不创建数组的情况下使用int?

时间:2014-10-21 17:20:08

标签: java arrays for-loop

我有以下脚本:

    public static void main(String[] args) 
    {
            String[] s1 = {"red", "white", "black", "blue"};
            String[] s2 = {"red", "black", "green"};
            String[] s3 = {"red", "green"};
            int red = 0;
            int black =0;
            int green = 0;
            int white= 0;
            int blue= 0;

            List <String> list = new ArrayList <String>();
            list.addAll(Arrays.asList(s1));
            list.addAll(Arrays.asList(s2));
            list.addAll(Arrays.asList(s3));

           for(String s: list)
           {
               if(s.equals("red"))
                {
                   red++;
                }
               else if(s.equals("white"))
                {
                   white++;
                }
               else if(s.equals("black"))
                {
                   black++;
                }
               else if(s.equals("green"))
                {
                   green++;
                }
               else  if(s.equals("blue"))
                {
                   blue++;
                }

           }
            System.out.println(red + "  Red found\n" + green + "  Green Found\n" + white + "  White Found\n" + black + "  Black Found\n" + blue + "  Blue Found");
    }
}

输出:

3  Red found
2  Green Found
1  White Found
2  Black Found
1  Blue Found

我遇到的问题是我正在添加为int,需要继续添加到System.out.println,有一些方法可以在不创建数组的情况下使用int吗?

2 个答案:

答案 0 :(得分:0)

如果我理解你需要什么是HashMap。您将检查地图是否包含例如“红色”键。如果它不包含它,则插入&lt;“red”,0&gt;否则你增加一个人找到的值 &LT; “红色”,1&GT;

HashMap<String,Integer> map = new HashMap<>();
String input = "red";
//for each input you will be doing:
if (!map.containsKey(input)) {

    map.put(input,0)
}
else {
    map.put(input,map.get(input)+1);
}

此外,如果您有一个Collection / ArrayList,我相信您也可以这样做:

int redOccurrences = Collections.frequency(colorsList, "red");

答案 1 :(得分:0)

可能会声明预期颜色的地图并将其用于计数:

public static void main(String[] args) 
{
    HashMap<String, Integer> allColorCount;

    //optionally pre-populate your map if you want it to be static colors
    allColorCount.put("blue", 0);
    //... repeat for all colors
    allColorCount.put("white", 0);

    /* 
     * your orig code for populating your lists
     */
     for(String s: list)
     {
        if(allColorCount.containsKey(s))
        {
            allColorCount.put(s, allColorCount.get(s)++);
        }
        //or if you want to dynamically map your counts:
        else
        {
           allColorCount.put(s, 1);
        }
     }

    //then at the end: 
    Set<String> colorSet = allColorCount.keyset();
    for(String currColor : colorSet)
    {
         System.out.println(allColorCount.get(currColor) + " " + currColor + " Found");
    }
}