I am new to programming. I've been in a class for a week now and I am stuck on this problem for most of my java programs. There was an exception for one of the programs where the code executed perfectly and showed the desired results.But for some of my other programs I have been getting the same error,
"Exception in thread "main" java.lang.ArrayOutOfBoundsException: 2.
I've been stuck on this for the past few days and I've searched everywhere online for a solution but there isn't any that works for my problem.
The following is a screenshot of my code. A simple program that takes three int command-line arguments and determines whether they constitute the side lengths of some right triangle.
This is the error I get when I run the code:
My class moves quickly so I am behind on other submissions so if you can please help me out.
I tried creating a program that determines whether three int values belong to a right-angled triangle. The assignment had two conditions;
I declared and assigned the integers and then created conditions to satisfy the assignment conditions. I expected to get the three values and the result of boolean isRightTriangle.
ArrayIndexOutOfBoundsException
is being thrown when you try to reference an array element using an index that's out of bounds. Valid indexes for any array
are greater or equal than 0
and smaller than array.length
, all possible indexes being integers. Whenever you use a numeric value that's outside these bounds, you get the exception mentioned in your question. The error message of
"Exception in thread "main" java.lang.ArrayOutOfBoundsException: 2.
Is telling you that the invalid index you are trying to use has a value of 2
. Which leads us to the conclusion that the line of
int c = Integer.parseInt(args[2]);
which is also suggested by the stack trace that tells you that the error was thrown at line 4. If you want to load values, you will need to append numeric values to your command that's running your application via CLI. Now, you will also need to check what's inside args
. It's quite possible that in the manner you call it, args[0]
is some text even if you specify numeric values to pass. So, let's append 1 2 3
to your CLI command and show what you have inside args
. If args[0]
is 1
, args[1]
is 2
and args[2]
is 3
, then your program should run successfully. If not, then you will need to adjust the manner you call it or the args indexes.