简体   繁体   English

基本计数器 arraylist 方法 java

[英]Basic counter arraylist in method java

I am trying to make a counter with a list of 10 elements in random position, the problem is that after making the complete tour of my array I must print on the screen how many numbers that are repeated.我正在尝试用随机 position 中的 10 个元素列表制作一个计数器,问题是在完成我的数组的完整浏览后,我必须在屏幕上打印重复的数字。

To do this, I made the method out of my Main space, I declared the array and the "for loop" to tour my array, the question is after that I must will include in the same method the counter?为此,我在我的主空间中创建了方法,我声明了数组和“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

Your method is taking an array as param, which is being assigned with a new array and the array itself not return.您的方法将数组作为参数,该数组被分配了一个新数组,并且数组本身不返回。 If the random values have to be generated in the method and only the number of repetitions needed, the parameter is not needed, And you also have a return statement after your first loop, making the rest of the code unreachable!如果必须在方法中生成随机值并且只需要重复的次数,则不需要该参数,并且您在第一次循环之后还有一个返回语句,使得代码的 rest 无法访问!

This being said, you could track the repetitions as follow:话虽如此,您可以按如下方式跟踪重复:

...
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"));
}
...

样品运行

Cheers!干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM