Click here to Skip to main content
15,886,640 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello!

Please bare with me. I know this question was asked before but I just can`t find a solution. This example that I recreated is taken from a JAVA tutorial website. i read that and recreated it. I have no idea how to fix this and how
Java
args[0]
is Out Of Bounds.

Here is the code:

Java
public class Sqrtcalc {
	
	public static void main (String[] args) {
		
		double b = Double.parseDouble(args[0]);
		double c = Double.parseDouble(args[1]);
		double a = Double.parseDouble(args[2]);
		
		double Delta = b*b - 4.0*a*c;
		double sqrootD = Math.sqrt(Delta);
		
		double N1 = (-b + sqrootD)/ (2.0*a);
		double N2 = (-b - sqrootD)/ (2.0*a);
		
		System.out.println(N1);
		System.out.println(N2);
		
	}

}


And this is the Error. If i remove
Java
double b
it just moves to the next value (Double c) and says the same thing.

Java
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at Sqrtcalc.main(Sqrtcalc.java:6)


line 6 being the one with Double b.

Thank you for your help and time!
Posted

First of all, it has nothing to do with Eclipse, which is just the IDE. When you run your application, it's out of equation.

The problem is very simple. The variable args means the array of string each representing command-line argument written in the command line when you start the application. Please see: https://en.wikipedia.org/wiki/Entry_point#Java[^].

Now, if you simply start the application with no command line, no arguments, the length of this array is zero. There are no any element, including, of course, args[0].

Solution: always check up the length of an array before accessing any element of an array by index.

(No, there is no a need to debug anything in this particular case; the problem is crystal clear. :-))

—SA
 
Share this answer
 
Your problem is that args do not contain what you expect.
The only way to know what is in args is to run the program with the debugger and inspect the variables, and particularly args.

You can make your code safer by checking the size of args before trying to use it.

For a solution, you need to give us the calling line for this code.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900