krstore krstore - 1 month ago 15
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).

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

Answer

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() ){
    array1.add(scanner.nextInt());
}

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] = iterator.next().intValue();
    }
    return ret;
}
Comments