比较字符串到数组元素?

时间:2014-10-17 14:19:07

标签: arrays string compare elements

我有以下代码:

public class Equals {

        String[] s1 = {"red", "white", "black", "blue"};
        String[] s2 = {"red", "black", "green"};
        String[] s3 = {"red", "green"};

我需要的是给我以下输出:

比较字符串s1,s2,s3

红色3场比赛。 黑色2场比赛。 绿色2场比赛。

有人可以帮帮我吗?

非常感谢!

问候!

1 个答案:

答案 0 :(得分:0)

这写得不是很好,但可以快速解决您的要求。基本上,我将所有数组添加到List中,然后遍历该列表,检查所选元素是否与任何给定颜色匹配。

    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