Search code examples
javaarrayscommand-line-argumentsclass-method

How to I get the middle number from three inputs in Java?


For example, if the user were to type in the command line argument:

java program 9 1 3.3

What formula would I use for the program to put it in order and print out: 3.3 is in between 1 and 9

I need three formulas, but what specifically would they be?


Solution

  • You can convert the 3 arguments args into a numeric array and sort it.

    public static void main(String[] args) {
        double[] numbers = new double[3];
        for (int i = 0; i < 3; i++) {
            numbers[i] = Double.parseDouble(args[i]);
        }
        Arrays.sort(numbers);
        ...
    }
    

    The major difference between this solution and the one provided by Jack Flamp is the sorting order: sorting numeric should use numerical order instead of lexicographical order (alphabetical order).

    UPDATE: However, when String is converted into double, we lose its exact representation: 1, 1.0, 1.00 are different in String, but all the same in double. In order to prevent this situation, you can do the conversion only for sorting:

    public static void main(String[] args) {
        Arrays.sort(args, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                double d1 = Double.parseDouble(s1);
                double d2 = Double.parseDouble(s2);
                return Double.compare(d1, d2);
            }
        });
        ...
    }