简体   繁体   中英

How do I sort an array in java?

Input has to taken by the user. My code is given below. Why does it only output zeroes? What is the solution?

Output of the program is 0 0 0 0 (total number of input taken).

import java.util.Arrays;
import java.util.Scanner;

public class atlast {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();
        int[] array = new int[107];
        for (int i = 0; i < n; i++) {
            array[i] = input.nextInt();
        }
        Arrays.sort(array);

        for (int i = 0; i < n; i++) {
            System.out.print(array[i] + " ");
        }
    }
}
int[] array = new int[107];

You are initializing a table that contains 107 value of 0. So, if the n is small, the first elements will be 0.

To see the result replace n in the last loop by 107 and you will see the values

You initialized an array with size 107 which implies there are 107 zeroes in the array initially before accepting the input from the user. Since there are four zeroes in the output, you must have taken 4 values for input. So there are four non-zero values and 103 zero values in the array. When you apply Arrays.sort 103 zeros comes before 4 non-zero values. Hence when you print n values (which is 4 in this case) you get only zeroes. You could use ArrayList instead so that numbers will be initialized only when user enters it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM