Home > Software engineering >  Finding the maximum of 3 numbers (user imput) in 3 different ways, in java?
Finding the maximum of 3 numbers (user imput) in 3 different ways, in java?

Time:06-09

I'm tasked with finding 3 ways to find the maximum of 3 numbers, in java, using user input.

So far, I have I only know 2.

The first is using a nested if / else statements in the format of, where one if - else is nested in the else portion of the main if - else statement.

The second way I know is, using the Math.max method where you can nest a Math.max ( x, Math.max ( x,y)).

Does anyone know the third way?

CodePudding user response:

In which data structure do you have values?

Array:

  int array[] = new int[]{10, 11, 88, 2, 12, 120};

  public static int getMax(int[] inputArray){ 
    int maxValue = inputArray[0]; 
    for(int i=1;i < inputArray.length;i  ){ if(inputArray[i] > maxValue){ 
         maxValue = inputArray[i]; 
      } 
    } 
    return maxValue; 
  }

Or:

    int[] arrayName = new int[] {1, 2, 3};
    Arrays.sort(arrayName);
    System.out.println(arrayName[arrayName.length - 1]);

List or another collection:

System.out.println(Collections.max(list));

Or:

Collections.sort(list);
System.out.println(list.get(list.size() - 1));

And also mentioned above variant:

int d = Math.max(a, b);
System.out.println(Math.max(c, d));

CodePudding user response:

You can nest the conditional operator as well.

int a, b, c; // the 3 numbers
int max = a > b && a > c ? a : b > a && b > c ? b : c;

In addition, TreeSet is a collection that sorts its elements. By default, integers are sorted in ascending order.

import java.util.TreeSet;
import java.util.Arrays;
// ...
int max = new TreeSet<>(Arrays.asList(a, b, c)).last();

CodePudding user response:

Seems like a pretty basic question but not with a solid practical reason. More useful would be to write a piece of code to fin max among a set or an array of numbers. But anyway, here're my possible solutions.

if (a > b) {
    if (a > c) {
        return a;
    }
}
if (b > c) {
    return b;
} else {
    return c;
}

Or neater one:

if (a > b) {
    if (a > c) {
        return a;
    }
}
return Math.max(b, c);

To see whether you figure this one out:

return a > b ? a > c ? a : c : b > c ? b : c;

Please never write something like i did above unless you want to impress someone with a piece of code nobody gets.

And much better version of the previous piece:

return a > b ? Math.max(a, c) : Math.max(b, c);
  •  Tags:  
  • java
  • Related