I am getting array bound error but to my mind, array starts from 0, so what is wrong with this code?
public class Quadratic {
public static void main(String
ArrayIndexOutOfBounds exception occur when you are trying to extract the variable at a wrong position in the array.
When you run a program in java after compilation e.x.javac hello
and then executing the class file by java hello
, the 0th position of the args[0]
will be the filename i.e. hello
in this case.
For you to successfully extract argument issued at the run time you have to use n+1 position in the array. For example. If I am running my program as java hello argument
I'll be using args[1]
if I wish to use the issued variable argument
at run time and so on for extracting the associated text.
If you are unsure whether your statement will generate an exception or not, it is always safe to use try & catch
block .Read - Exception Handling
You don't have an item in args[0] and/or args[1]. You need to check that there are enough arguments in the array.
double b = args.length>=1?Double.parseDouble(args[0]):0.0;
double c = args.length>=2?Double.parseDouble(args[1]):0.0;
If there are no arguments in the array, then it means that you didn't pass an argument into the program or you didn't pass enough arguments.
Protect yourself: be defensive.
public class Quadratic {
public static void main(String[] args) {
if (args.length> 1) {
double b = ((args.length > 0) ? Double.parseDouble(args[0]) : 0.0);
double c = ((args.length > 1) ? Double.parseDouble(args[1]) : 0.0);
double discriminant = b*b - 4.0*c;
double sqroot = Math.sqrt(discriminant);
double root1 = (-b + sqroot)/ 2.0;
double root2 = (-b - sqroot)/ 2.0;
System.out.println(root1);
System.out.println(root2);
} else {
System.out.println("two arguments are required: b and c, please");
}
}
}
What happens if the discriminant is negative? What if it's zero?
Why are you restricting yourself to the case where a = 1?
Try and debug it. print the size of args using System.out.println(args.length);
.
if the size is smaller then 2 your not getting the parameters to your main class.