问题描述:

I am developing a Java application.

I have five int variables. They may contain different int values. I want to check which variable is the biggest. Depending on that variable, I have to execute different method.

int intHx;

int intEx;

int intRx;

int intMx;

int intIx;

How can I find the variable with the highest value?

PS: To Clarify

I want to pick the variable with highest value, not the value that variable contain. This is not related to sorting values, but executing different method.

网友答案:

This enum is optional, but helps with code clarity:

enum Field {
    INT_HX,
    INT_EX,
    INT_RX,
    INT_MX,
    INT_IX
}

Then test the values:

Field largestField = Field.INT_HX;
int largestValue = intHx;
if(intEx > largestValue) {
    largestField = Field.INT_EX;
    largestValue = intEx;
}
if(intRx > largestValue) {
    largestField = Field.INT_RX;
    largestValue = intRx;
}
if(intMx > largestValue) {
    largestField = Field.INT_MX;
    largestValue = intMx;
}
if(intIx > largestValue) {
    largestValue = intIx;
}
switch(largestField) {
    case INT_HX:
        // call the intHx related method
    break;
    case INT_EX:
        // call the intEx related method
    break;
    case INT_RX:
        // call the intRx related method
    break;
    case INT_MX:
        // call the intMx related method
    break;
    case INT_IX:
        // call the intIx related method
    break;
}
网友答案:

Try this (Required JDK 8 )

 private int getMax(int... numbers){
    OptionalInt max = Arrays.stream(numbers).max();
    return max.getAsInt();
 }
网友答案:
Field largestField;
if (num1>num2)
{
   largestField = Field.num1;
}
else
{
   largestField = Field.num2; 
}
if (largest < num3)
{
   largestField = Field.num3;
}
if (largest < num4)
{
   largestField = Field.num4;
}
if (largest < num5)
{
   largestField = Field.num5;
}

At the end the value inside largest will be the largest among 5.

相关阅读:
Top