Home > Software engineering >  Figure out largest value in array of numbers
Figure out largest value in array of numbers

Time:12-03

I want to be able to calculate the largest value in a list of numbers

I want the type of number to be any number (it should work with double, int, long, etc)

The method that I tried to create for this is not working and keeps returning the first value of the array

public static <V extends Number & Comparable<V>> V max(final V... numbers) {
    V currentLargest = numbers[0];
    for (V value : numbers) {
        int arraySize = 0;
        if (currentLargest.compareTo(numbers[arraySize]) < 0) {
            currentLargest = numbers[arraySize];
        }
        arraySize = arraySize   1;
    }
    return currentLargest;
}

I dont know what I am doing wrong

CodePudding user response:

Okay, there are a few issues with the code you have written. First off, I would recommend putting in a check to make sure the numbers array is not null. While this is not required, I would still recommend it. However, the most significant issue you are having is how you are attempting to compare your currentLargest value to a value on the array. You are always comparing against the first value of the array every single time as you have your arraySize variable updated to zero with every iteration of your loop.

I created a method that does exactly what you are asking with the bugs from your method fixed. I hope this helps.

    public static <V extends Comparable<? super V>> V max(final V... numbers) {
        if (numbers == null || numbers.length == 0) {
            return null;
        }
        V currentLargest = numbers[0];
        for (int i = 1; i < numbers.length; i  ) {
            if (currentLargest.compareTo(numbers[i]) < 0) {
                currentLargest = numbers[i];
            }
        }
        return currentLargest;
    }
  • Related