krstore krstore - 1 year ago 84
Java Question

array with zero values

If the import integers are

5 2 1 12 2 10 4 13 5

However, the output shows with many "0" if the arraysize is large(20 now).

enter image description here
Therefore, I may ask which parts go wrong and any solution to fix the null parts.

Answer Source

If the zeros are your problem, than don't initialize your array with a constant value ("20", in your example).

Just change your scanning code to:

Scanner scanner = new Scanner(new File("C:/text.txt"));
ArrayList<Integer> array1 = new ArrayList<Integer>();

while(scanner.hasNextInt() ){

Also, you will need to convert your ArratList to an int array. The following code will help (copied from : How to convert an ArrayList containing Integers to primitive int array?):

public static int[] convertArrayListToIntArray(List<Integer> integers)
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
        ret[i] =;
    return ret;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download