Nishi Perera
Nishi Perera

Reputation: 23

Getting the max variable out of the given variables

I want to find the variable having the maximum value from three variables. Im using the given code to find the maximum value, but it only can output the maxium value.I want to get the variable having the maximum value.any methods?

int x=1;
 int y=2;
 int z=3;
          int max =  Math.max(Math.max(x,y),z);
          System.out.println(max); 

Upvotes: 0

Views: 87

Answers (2)

paymaster
paymaster

Reputation: 41

If you only want to know the name of the variable with the max value, that's easy, put (value, var name) into hashmap. After you get the max value among three, find the var name from hash map by using the max value as the key.

Upvotes: 0

DJClayworth
DJClayworth

Reputation: 26856

If you want to do different things based on which of three variables has the highest value, you can't do better than:

if (x > y && x > z) {
   // do stuff for when x is biggest
} else if (y > x && y > z) {
    // do stuff for when y is biggest
} else {
    // do stuff for when z is biggest
}

I deliberately didn't cover the case when two variables have the same value, both the highest, because you didn't say what you wanted to do. I'll leave that as an exercise for the reader.

If you have many more than three variables it gets more complicated, and you need a way of mapping a variable to an action.

Upvotes: 2

Related Questions