For-Each Loop Java Error ArrayIndexOutOfBoundsException

后端 未结 6 1983
感情败类
感情败类 2020-12-10 07:51

In my program I need a for-each loop which counts the number of evens in the given array and increments the variable even for each one. When I use a standard

6条回答
  •  -上瘾入骨i
    2020-12-10 08:25

    Though there are lot many answers. You could achieve same by using java-8 streams as well. Use reducer to find out the even's count and then from length reduce the even's count to get odd's count.

    See code below:-

       int[] numbers = new int[8];
    
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = (int) (Math.random() * 51 + 50);
        }
    
        int even = Arrays.stream(numbers)
                .reduce(0, (a, b) -> {
                    a += b % 2 == 0 ? 1 : 0;
                    return a;
                });
        int odd = numbers.length - even;
    

提交回复
热议问题