user1837411
user1837411

Reputation: 53

How to write a method that takes int variables and returns the largest?

I am trying to write a method that compares 3 numbers and returns the largest of them.

This is my code, but it doesn't work...

public int max(int x, int y, int z){
    return Math.max(x,y,z);
} 

How can my code be corrected?

Upvotes: 3

Views: 12530

Answers (5)

Bohemian
Bohemian

Reputation: 425033

Try using the JDK api:

public static int max(int i, int... ints) {
    int nums = new int[ints.length + 1];
    nums[0] = i;
    System.arrayCopy(ints, 0, nums, 1, ints.length);
    Arrays.sort(nums);
    return ints[nums.length - 1);
}

Upvotes: 0

Maciej Ziarko
Maciej Ziarko

Reputation: 12084

If Apache Commons Lang is on your classpath, you can use NumberUtils.

There are several max, min functions. Also one you wanted.

Check API: http://commons.apache.org/lang/api/org/apache/commons/lang3/math/NumberUtils.html

Commons Lang is useful as it extends standard Java API.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

For any number of int values, you can do this (tip 'o the hat to zapl):

public int max(int firstValue, int... otherValues) {
    for (int value : otherValues) {
        if (firstValue < value ) {
            firstValue = value;
        }
    }
    return firstValue;
}

Upvotes: 4

Reimeus
Reimeus

Reputation: 159784

For your current solution of 3 integer arguments, you could replace:

Math.max(x,y,z)

with

Math.max(Math.max(x, y), z)

The javadoc shows that Math.max takes 2 arguments.

Upvotes: 4

wattostudios
wattostudios

Reputation: 8764

Try this...

public int max(int x, int y, int z){
    return Math.max(x,Math.max(y,z));
} 

The method Math.max() only accepts 2 arguments, so you need to perform this method twice if you want to compare 3 numbers, as per the code above.

Upvotes: 5

Related Questions