Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException problem on mac
No matter whatever other code i write on my mac apart from the very popular Hello World, no other one seems to work on my mac.
Code Java:
public class Distance1 {
public static void main(String[] args){
int a = Integer.parseInt( args[0] );
int b = Integer.parseInt( args[1] );
int dist = Math.max(a,b) - Math.min(a,b);
System.out.println( dist );
}
}
The error i get is: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Distance1.main(distance1.java:4)
Since i'm just a beginner, i dont know what it means. Can any1 help me with it? :)
Re: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException problem on mac
DOes the args array contain any elements? Use the .length attrubute to test if there are enough elements in the array before trying to access any of its elements.
If the array is empty there is no first element (index=0) and you'll get: ArrayIndexOutOfBoundsException: 0
The args array is filled with what is on the command line when the java command starts the class. For example:
java TheClass thisIsArg1 thisIsArg2
when the main() method executes, args[0] would have the value: "thisIsArg1", and args[1] would be "thisIsArg2"
Re: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException problem on mac
i think you are not provide the command line arguments. Run the program with command line arguments like
> java Distance1 4 5
Re: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException problem on mac
Thanks to all of you who answered but now I get a different error:
Distance1.java:7: cannot find symbol
symbol : variable max
location: class java.lang.Math
System.out.println(Math.max - Math.min);
^
Distance1.java:7: cannot find symbol
symbol : variable min
location: class java.lang.Math
System.out.println(Math.max - Math.min);
^
2 errors
And now i'm confused :S
Re: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException problem on mac
Where did you see that the max and min variables are defined in the Math class?
The compiler can not find their definitions in the Math class.
Read the API doc for the Math class to see what variables and methods are in the class and how to use them.
See post#1 for some usages of Math methods.
Re: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException problem on mac