如果java中不存在奇数,如何在数组中找到最高奇数并返回0?

xj3cbfub  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(259)

如何在数组中找到最高奇数并将其打印到标准输出?如果数组没有奇数,它应该返回0。
我已经写了这个程序,但是不知道如何在数组中找不到奇数的情况下返回0。

public class Highestodd_number {

    public int odd() {
        int[] arr = { 4, 6, 9};
        int max = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0 && arr[i] > max) {
                max = arr[i];
                System.out.println(max);
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        Highestodd_number rt = new Highestodd_number();
        rt.odd();
    }
}
cgfeq70w

cgfeq70w1#

可以使用java 8流和较少的样板代码来实现此任务:

public static int findMaxOddOr0(int[] arr) {
    return Arrays.stream(arr)               // convert array to IntStream
                 .filter(x -> x % 2 != 0)   // filter all odd values
                 .max()                     // find optional max
                 .orElse(0);                // or 0 if no max odd is found
}

public static void main(String args[]) {
    int[][] tests = {
        {4, 6, 9},
        {2, -2, 8, 10},
        {-5, -7, -3, 12}
    };

    Arrays.stream(tests)
          .forEach(arr -> 
              System.out.printf("%s -> %d%n", Arrays.toString(arr), findMaxOddOr0(arr)));
}

输出:

[4, 6, 9] -> 9
[2, -2, 8, 10] -> 0
[-5, -7, -3, 12] -> -3

相关问题