【问题标题】:How to count the amount of times a specific String appears [duplicate]如何计算特定字符串出现的次数[重复]
【发布时间】:2020-05-24 00:33:42
【问题描述】:

我目前被困在这个程序上,其目标是输入数组的大小,然后输入数组的每一行颜色字符串。每一行可以适应多种颜色。通过使用另一种方法来检查如果该行包含至少 50% 或更多的蓝色,它将返回“通过”值或“失败”值。示例输入:

2 蓝色 红色 绿色 蓝蓝橙红

示例输出:

失败 通过

我的问题出在代码第 39 行的检查方法中,我最终在这一行 if(x[i].contains(blue)) 中得到了 NullPointerException

有没有一种有效的方法来计算“蓝色”出现的次数并将其添加到计数器中?

代码如下:```

public class BigBlue {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = input.nextInt();
        String[] list = new String[x];
        String inputs = input.next();
        for(int i = 0;i < list.length;i++) {
            for(int j = i; j < i; j++) {
            if(inputs == "blue") {
                list[i] = inputs;
            }
            else if(inputs == "orange") {
                list[i] = inputs;
            }
            else if(inputs =="red") {
                list[i] = inputs;
            }
            else if(inputs == "green") {
                list[i] = inputs;
            }
            else {
                System.out.println("Invalid input");
            }
            }
        }
        System.out.println(check(list));

    }

    public static String[] check(String[] x) {
        String[] j = new String[x.length];

        for(int i = 0; i < x.length;i++) {
            int wordCount = 0;
            int counter = 0;
            if(x[i].contains("blue")) {

                counter++;
            }
            String trim = x[i].trim();
            wordCount = trim.split("\\s+").length;
            int k = wordCount / 2;
            if(counter >= k) {
                j[i] = "Passed";
            }
            else {
                j[i] = "Failed";            }
        }
        return j;
    }

}

【问题讨论】:

    标签: java arrays string loops int


    【解决方案1】:

    使用ArrayList 而不是简单的数组,因为ArrayListsize() 运算符返回元素的实际数量,而不是可能的最大元素数量。

    你可以使用HashMap来统计元素个数:

    String[] inputArray = {"a", "a", "b", "b", "b", "b", "a", "a", "a", "b", "c", "c", "c", "e", "c", "d", "d", "c", "c", "c", "c", "d"};
    
    Map<String, Integer> map = new HashMap<String, Integer>();
    
    for (String element : inputArray) {
        Integer count = map.get(element);
    
        // Increase the counter
        if (count == null) {
             count = 1;
        } else {
             count++;
        }
    
        map.put(element, count);
    }
    

    最后,地图包含了每个不同字符串的计数。

    只有 10 个元素,您的嵌套循环可能会更快,但随着您拥有的元素越多,HashMap 将变得越快(相对于嵌套循环)。

    【讨论】:

      【解决方案2】:

      您可以尝试使用 count 之类的变量,然后只使用 count++?

      【讨论】:

        猜你喜欢
        • 2020-06-14
        • 2011-07-08
        • 2019-12-10
        • 2012-05-31
        • 2011-05-03
        • 1970-01-01
        • 2017-09-24
        相关资源
        最近更新 更多