Jarod Wood
Jarod Wood

Reputation: 1

Sort the integers of an Array

I'm trying to sort the integers of an array, but I keep getting errors with what I try. I've tried sort(array); array.sort(); Arrays.sort(array); and Arrays.sort(); but nothing works. Help would be appreciated. The error I get for this Arrays.sort(array) is Cannot find symbol, symbol variable Arrays location: class Main

  public static void main(String[] args) {
    int[] array = new int[20];
    array = fillArray(array);
    printArray(array);
    array = sortArray(array);
    printArray(array);
}

public static int[] fillArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        array[i] = (int) (1 + Math.random() * 99);

    }

    return array;
}

public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        if (i > 0) {
            System.out.print(" | ");
        }
        System.out.print(array[i]);

    }
}

public static int[] sortArray(int[] array) {

    Arrays.sort(array);
    return array;

}

}

Upvotes: 0

Views: 192

Answers (2)

Boann
Boann

Reputation: 50021

Your code does work. (It does sort the array.) I believe your confusion might be because the unsorted and sorted output of printArray appear together on the same line and it is very hard to see. Put a line break at the end of the printArray method, and it will be clear that the result is sorted:

System.out.println();

The output now is (for example):

78 | 42 | 88 | 11 | 40 | 64 | 37 | 78 | 42 | 35 | 77 | 33 | 33 | 5 | 89 | 12 | 32 | 86 | 24 | 79
5 | 11 | 12 | 24 | 32 | 33 | 33 | 35 | 37 | 40 | 42 | 42 | 64 | 77 | 78 | 78 | 79 | 86 | 88 | 89

Edit: Based on the error message you've now provided, the problem is that Arrays is a class in the java.util package, and you haven't imported the class or qualified access to it. Put this line at the top of the file:

import java.util.Arrays;

Or, when you call the method, use what is called its "fully-qualified name":

java.util.Arrays.sort(array);

See Using Package Members in the Java tutorial for the details.

Upvotes: 2

Mengjun
Mengjun

Reputation: 3197

Actually, the code you used is working.

You can make some change in main method to make the array printed in console more cleraly.

like

    System.out.println("Before sorting...");
    printArray(array);
    array = sortArray(array);
    System.out.println("\nAfter sorting...");
    printArray(array);

An run example is as follows:

Before sorting...
47 | 68 | 94 | 17 | 99 | 60 | 92 | 61 | 44 | 99 | 64 | 37 | 15 | 79 | 38 | 52 | 77 | 41 | 62 | 88
After sorting...
15 | 17 | 37 | 38 | 41 | 44 | 47 | 52 | 60 | 61 | 62 | 64 | 68 | 77 | 79 | 88 | 92 | 94 | 99 | 99

Upvotes: 0

Related Questions