Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

  • Context: Java 
  • Thread starter Thread starter MathematicalPhysicist
  • Start date Start date
  • Tags Tags
    Thread
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 3K views
Messages
4,662
Reaction score
372
I have the following code
Java:
public class Assignment1 {

    public static void main(String[] args) {
        int x= Integer.parseInt(args[0]);
        int y= Integer.parseInt(args[1]);
        int z= Integer.parseInt(args[2]);
        if (x<0 || y<0 || z<0) {
            System.out.println("Invalid input!");
        }
        else {
            if(x*x+y*y==z*z) {
                System.out.println("The input ("+x+","+y+","+z+") defines a valid triangle!");
            }
            else {
                System.out.println("The input ("+x+","+y+","+z+") does not define a valid triangle!");
            }
        }

    }

}
And then I get this annoying error in the terminal, that says the following:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Assignment1.main(Assignment1.java:4)
So it seems the error is at line 4, i.e
int x = Integer.parseInt(args[0]);

How would you fix this error?

Thanks!
 
Physics news on Phys.org
The args array is the way you access the command line arguments when you run your program.

I suspect you ran it from an IDE and didn't provide any arguments to the program. IF you were to check the size of the args array you would find it to be 0. Hence your error when you tried to access element from a zero element string array.

From the command line, you might type:
Java:
java -jar mypgm.jar my.homework.Assignment1 1 2 3
Java would search the mypgm.jar for the Assignment1 class and would pass the arguments 1, 2, 3 as a string array to it.
 
When I'm testing my programs in an IDE I often use the trick below:
Java:
if(args.length == 0) {
    args = "1 2 3".split(" ");
}

It allows you test in the confines of an IDE with known command line arguments.

However, for a production level program you would replace the args= "1 2 3".split(" ") with a help msg to show the expected syntax of your program.