Question

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();

    }


}
Was it helpful?

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.

OTHER TIPS

Put this after the for loop:

java.util.Arrays.sort(numbers);

notice numbers not numbers[i] and the print needs to come out of that loop too.

The mistake you're making is that you are trying to sort a single number. The error message points out that the sort method expects an array.

Your algorithm should first read in all the numbers, before sorting. So change your code to something like this:

...

// first read in numbers
for ( int i = 0; i < numbers.length; i++){
    numbers[i] = input.nextDouble() ;
}

// then apply sort
java.util.Arrays.sort(numbers); // numbers is an array, so it's a valid argument.

// finally, after sorting you may now output the sorted array
for(int number : numbers){
    System.out.println(number);
}

...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top