Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

  • #1
MathematicalPhysicist
Gold Member
4,308
216
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!
 

Answers and Replies

  • #2
12,078
5,748
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.
 
  • #3
12,078
5,748
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.
 
  • #4
MathematicalPhysicist
Gold Member
4,308
216
@jedishrfu OK, I fixed it I typed the following command after compiling the java file:
Code:
java Assignment1 1 2 3
Thanks!
 
  • Haha
Likes jedishrfu

Related Threads on Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Replies
2
Views
38K
  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
7
Views
3K
  • Last Post
Replies
3
Views
559
Replies
2
Views
4K
Replies
4
Views
541
Replies
4
Views
15K
Replies
19
Views
4K
Replies
17
Views
6K
Top