Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Figure out largest value in array of numbers

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading