Search code examples
javaarrayscommand-line-argumentsbubble-sort

Command line arguments is causing Exception in "main" thread


import java.util.*;

public class bubblesort {
        public int input;
        public int c;
        public int d; 
        public int swap;
        public int[] arr= new int[input];
        Random rand = new Random();
        Scanner in = new Scanner(System.in);

    public static void main(String[] args) { 
        bubblesort b = new bubblesort();
        Scanner in = new Scanner(System.in);
        System.out.println("Ascending(1),Descending(2),Random(3)");
        int arrayInput= in.nextInt();

        if (arrayInput == 1) {
            b.ascending(args);
            }
        else if (arrayInput == 2) {
            b.descending(args);
            }   
        else if (arrayInput == 3) {
            b.random(args);
            }           
    }


    public void ascending(String[] args){   
        this.input = Integer.parseInt(args[0]);

        for (c = 0; c < input; c++){ 
          arr[c] = rand.nextInt(Integer.MAX_VALUE);
          }

        for (c = 0; c < ( input - 1 ); c++) {
            for (d = 0; d < input - c - 1; d++) {
             if (arr[d] > arr[d+1]){
                  swap       = arr[d];
                  arr[d]   = arr[d+1];
                  arr[d+1] = swap;
                }
            }
        } 
        for (c = 0; c < input; c++) 
        System.out.println(arr[c]);

        long startTime = System.nanoTime();
        for (c = 0; c < input - 1; c++){
            for (d =0; d < input - c -1 ; d++){
                if (arr[d] > arr[d+1]){
                     swap = arr[d];
                     arr[d] = arr[d+1];
                     arr[d+1] = swap;
                     }
                }
            }
        long endTime = System.nanoTime();
        long estimatedTime = endTime - startTime;
        System.out.println("Sorted list of numbers");
        for (c = 0; c < input; c++) 
        System.out.println(arr[c]);
        System.out.println("The time it takes to sort an descending array into an ascending array is "+estimatedTime+" nano seconds");
        }
    }

So when I compile this file (this isn't my whole file) it compiles, its just when i try to run it it gives the the exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at bubblesort.ascending(bubblesort.java:61)
    at bubblesort.main(bubblesort.java:23)

I think the problem is that the array length, or i called it "input" is not changing to the command line argument integer, so input stays at zero. If this is so, how can I fix this problem?


Solution

  • You can't initialize arr before you parse the user input. The statement public int[] arr= new int[input]; results with an array of size 0 so any attemt to access it will throw an exception. Try initializing the array inside the main, after parsing the array length.