【问题标题】:Basic counter arraylist in method java方法java中的基本计数器arraylist
【发布时间】:2019-10-26 14:59:52
【问题描述】:

我正在尝试用随机位置的 10 个元素列表制作一个计数器,问题是在完成我的数组的完整浏览后,我必须在屏幕上打印有多少重复的数字。

为此,我在我的主空间中创建了方法,我声明了数组和“for循环”来浏览我的数组,问题是之后我必须在相同的方法中包含计数器吗? ...

public static int Vectores(int a[]) {
    // Declared variable
    a = new int[10];
    int lf = a.length;

    // Here we will tour the array and then complete the arrays with random numbers.
    for (int i = 0; i < lf; i++) {
        a[i] = (int) (Math.random() * 100);
        System.out.println(" A:" + a[i] );
    }
    return a[i];

    // Here will be an "if condition" + and for loop to the counter 
    int counter = 0;
    for (int i = 0; i < 10; i++) {
    }
} // END

【问题讨论】:

标签: java


【解决方案1】:

您的方法将一个数组作为参数,它被分配了一个新数组并且数组本身不返回。如果必须在方法中生成随机值并且只需要重复次数,则不需要该参数!而且您在第一个循环之后还有一个 return 语句,使其余代码无法访问!

话虽如此,您可以按如下方式跟踪重复:

...
int a[] = new int[10];
Map<Integer, Integer> count = new HashMap<>();

for (int i = 0; i < a.length; i++) {
    a[i] = (int) (Math.random() * 10);
    count.compute(a[i], (k, ov) -> ov != null ? ++ov : 1);
}

List<Entry<Integer, Integer>> repetitions = count.entrySet().stream()
                                             .filter(e -> e.getValue() > 1)
                                             .collect(Collectors.toList());

// Return the value & or display the details
if (repetitions.isEmpty()) {
    System.out.println("No repetition found !");
} else {
    System.out.println("Number of value which are repeated : " + repetitions.size());
    repetitions.forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue() + " times"));
}
...

干杯!

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 2023-01-25
    • 2016-06-07
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多