-1

I have the task where the array resuslts" should be returned with only two values from all the array: minimum and maximum values. But the code does not do it. What's wrong? Please help me to correct the code in order to return the array with minimum and maximum values. Fill free to clarify or ask additional issues. By the conditions of the task I have not to use any other methods (Maths or strems). only loops and arrays.

public class Stat {
    public static int[] getStat(int[] results) {
        int min = 0;
        int max = 0;
        for(int i=0;i<results.length;i++){
            if(results[i] < min){
                min = results[i];
            }
            if(results[i] > max) {
                max = results[i];
            }
        }
        return new int[] { min, max };
    }
}
  • Your minimum value will be 0 if your minimum value in results is 1. Because 0 is lesser than 1. – Kv1402 Aug 22 '22 at 11:38
  • _But the code does not do it._ It does for me. [Edit] your question and post the code that calls method `getStat`. Also post the result that you are getting (or if you are not getting a result or if you are getting an error). And if you are getting a result then write why the result is wrong. – Abra Aug 22 '22 at 11:44
  • The problem is that you initialize `min` with 0, initially making 0 the lowest number in your array. Try to initialize `min` with the highest possible int value (which is `Integer.MAX_VALUE`). Likewise, `max` should be initialized with `Integer.MIN_VALUE`. – MC Emperor Aug 22 '22 at 11:48
  • When i applied: min = Integer.MAX_VALUE; max = Integer.MIN_VALUE; Following mistakes appeared. Compile error: /Stat.java:4: error: cannot find symbol min = Integer.MAX_VALUE; ^ symbol: variable min location: class Stat/Stat.java:5: error: cannot find symbol max = Integer.MIN_VALUE; By the conditions of the task I have not to use any other methods (Maths or strems). only loops and arrays. – Andrew Trendy Aug 22 '22 at 13:37

2 Answers2

0

Initialize min = Integer.MAX_VALUE and max = Integer.MIN_VALUE

0
public static int[] getStat(int[] arr) {
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    for (int num : arr) {
        min = Math.min(min, num);
        max = Math.max(max, num);
    }

    return new int[] { min, max };
}

Or using streams:

public static int[] getStat(int[] arr) {
    int min = Arrays.stream(arr).min().orElse(0);
    int max = Arrays.stream(arr).max().orElse(0);
    return new int[] { min, max };
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35