-1

I have just started out with Java and I am playing around with codes I copied online. I copied this code online and tried to run it on eclipse

http://introcs.cs.princeton.edu/java/12types/SpringSeason.java.html

public class SpringSeason { 
    public static void main(String[] args) { 
        int month = Integer.parseInt(args[0]);
        int day   = Integer.parseInt(args[1]);
        boolean isSpring =  (month == 3 && day >= 20 && day <= 31)
                         || (month == 4 && day >=  1 && day <= 30)
                         || (month == 5 && day >=  1 && day <= 31)
                         || (month == 6 && day >=  1 && day <= 20);

        System.out.println(isSpring);
    }
}

and I keep getting this error on eclipse

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at trollstartwo.main(trollstartwo.java:4)

1 Answers1

1

The args[0] refers to the String array args[] which is a parameter of the main method.

.... void main(String[] args) //this args array here

The values of the args[] array are provided by the user while running the program. While running the program, you might see an option in Eclipse for main method arguments. You have to provide the values for args[0] and args[1] there. If you don't do that, the array args[] is not even initialised, i.e., it remains an array of 0 spaces. So when the program tries to access the values at 0 and 1 position of args[], it doesn't even find those positions and thus the ArrayIndexOutOfBounds exception is thrown during runtime.

To avoid this, provide values in the main method arguments box. Suppose if you wanna provide '4' for month and '5' for day, type {"4", "5"} in the box.