Search code examples
javasortingdouble-precision

double precision numbers into an array, then sort and display number from lowest to highest


In line 24, I am getting an error which is commented out. What is causing this and how to I get it fixed?

Any help is much appreciated. Thanks ahead of time. :)

import java.util.Scanner;

public class main {


    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //initialize array
        double[] numbers = new double [10];

        //Create Scanner object
        System.out.print("Enter " + numbers.length + " values: ");

        //initialize array
        for ( int i = 0; i < numbers.length; i++){
            numbers[i] = input.nextDouble() ;
            java.util.Arrays.sort(numbers[i]); //getting an error here, thay says [The method sort(int[]) in the type Arrays is not applicable for the arguments (double)]
        //Display array numbers
        System.out.print(" " + numbers);            
        }

        //Close input
        input.close();

    }


}

Solution

  • You need to sort the complete array rather than a single element:

    Arrays.sort(numbers);
    

    Better to move it outside of the for-loop. You could use Arrays.toString to display the contents of the array itself:

    for (int i = 0; i < numbers.length; i++) {
       numbers[i] = input.nextDouble();
    }
    Arrays.sort(numbers);
    System.out.print(Arrays.toString(numbers));
    

    Note: Class names start with an uppercase letter, e.g. MyMain.