Your code is still wrong, even if you force it to print. To find the difference between the minimum and maximum, use this method:
public static OptionalInt range(int... array) { OptionalInt range = OptionalInt.empty(); if (array != null && array.length > 0) { int min = array[0]; int max = min; for (int n : array) { if (n < min) { min = n; } else if (n > max) { max = n; } } range = OptionalInt.of(max - min); } return range; }
You can call it in two ways:
int[] arr = {2, 4, 6, 8}; OptionalInt range = range(arr);
or
OptionalInt range = range(1, 2, 3, 5);
The method returns an OptionalInt , not a number, because there is not always a minimum and a maximum. They are not present when the array is empty or when there is no array itself and the method received null .
To print the OptionalInt you can use the ifPresent() method, or, starting with Java 9, the ifPresentOrElse() method. For example:
int[] arr = {2, 4, 6, 8}; range(arr).ifPresentOrElse(System.out::println, () -> System.out.println("no range")); arr = null; range(arr).ifPresentOrElse(System.out::println, () -> System.out.println("no range")); arr = new int[0]; range(arr).ifPresentOrElse(System.out::println, () -> System.out.println("no range")); range(1, 2, 3, 5).ifPresent(System.out::println); range().ifPresent(System.out::println); // ничего не напечатает range(null).ifPresent(System.out::println); // ничего не напечатает
Using sorting, to find the minimum and maximum, is less efficient.