0

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.

ChrisB
  • 2,497
  • 2
  • 24
  • 43
krstore
  • 3
  • 3

2 Answers2

0

By doing this in your code:

int [] array1 = new int [20];

You are saying, initialize array1 with 0 as a default value for all.

Now if you enter only 10 values, rest of the 10 values will be zero.. hence when sorted.. 0 is less than 1 it appears first..

clear?

0

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;
}
Community
  • 1
  • 1
MordechayS
  • 1,552
  • 2
  • 19
  • 29
  • @krstore - see the link added. Because my answer requires you to change your data-structure from a primitive int array to an array list, and I don't want you needing to change all of your other methods (int[]->ArrayList) - I added a conversion method. – MordechayS Oct 20 '16 at 17:38
  • @krstore I changed the method's name. Better now? – MordechayS Oct 20 '16 at 17:47
  • cannot find symbol - class iterator ? – krstore Oct 20 '16 at 17:52
  • oh I see, I finally get it right. thank you for your passionate – krstore Oct 20 '16 at 18:31
  • @krstore Happy to help, and welcome to Stack Overflow. If this answer or any other one solved your issue, please mark it as accepted. – MordechayS Oct 20 '16 at 19:01