用于检查数组中重复值的java方法为每个重复值输出新行

fafcakar  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(249)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

上个月关门了。
改进这个问题
我在java中创建了一个方法,用于检查(并计数)数组中的重复值:

private static void checkDuplicates(String[] array)
    {
    int arrayLength = array.length;
        for (int i = 0; i < arrayLength; i++) {
            int count = 0;

            for (int i2 = 0; i2 < arrayLength; i2++) {
                if (array[i].equals(array[i2])) {
                    count++;
                }
            }
            System.out.println("The value " + array[i] + " appears " + count + " times in the array.");
            }
            }

给定数组{string1,string1,string2,string3,string1},这将生成以下输出:

The value string1 appears 3 times in the array.
The value string1 appears 3 times in the array.
The value string2 appears 1 times in the array.
The value string3 appears 1 times in the array.
The value string1 appears 3 times in the array.

正如您现在可能已经理解的,我不希望程序为重复数组元素的每次出现打印一行。
我相信这个问题有一个简单的解决办法,但我已经在这方面工作了几个小时,我不能找出它。有人能给我指出正确的方向吗?

ckx4rj1h

ckx4rj1h1#

我很想知道你的目标。这对你来说是一个训练练习吗?你只允许使用数组,到目前为止你的训练还有限吗?
我同意前面的回答,他们建议用Map。使用数组存储计数会变得很混乱,因为需要两个对应的数组。这些数组的长度是固定的,可能太长了。例如:string[]texts=new string[array.length];int[]counts=新int[array.length];一个Map,例如hashmap是推荐的hashmap<string,integer>不要忘记导入java.util.hashmap;
您的代码可能是这样的(我尽量保留您的示例)

public static void main(String[] args) {
        String[] duplicates = new String[]{"string1", "string1", "string2", "string3", "string1"};
        checkDuplicates(duplicates);
    }

    private static void checkDuplicates(String[] array)
    {
        HashMap<String, Integer> duplicateCounter = new HashMap<String, Integer>();

        for(int i=0; i<array.length; i++){
            if(duplicateCounter.containsKey(array[i])){
                //the HashMap already has an entry with this key, so 1 should be added
                //array[i] is of course the String, for example "string1"
                duplicateCounter.put(array[i], duplicateCounter.get(array[i])+1);
            }
            else{
                //the HashMap does not contain your string. A first entry has to be made
                duplicateCounter.put(array[i], 1);
            }
        }
        //Now print your HashMap
        for(String word:duplicateCounter.keySet()){
            System.out.println("The value " + word + " appears " + duplicateCounter.get(word)+ " times in the array.");
        }

    }
hujrc8aj

hujrc8aj2#

当您扫描“此事件在此数组中发生的频率”时,如果您发现某个引用的索引低于您的索引,则该较低索引的循环将已打印此引用。
因此,在这种情况下,不要打印任何内容。在你的代码方面,而不是 count++ ,改为:检查 i2 低于 i . 如果是,请采取措施确保不打印,否则,不要这样做(提示:您可以创建一个新的局部变量。可能是那种类型的 boolean ?).

相关问题