主方法中的ArrayIndexOutOfBounds异常 [英] ArrayIndexOutOfBounds exception in main method
本文介绍了主方法中的ArrayIndexOutOfBounds异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到数组绑定错误,但我认为数组从0开始,那么这段代码有什么问题呢?
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[] args) {
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
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);
}
}
推荐答案
保护自己:保持防御.
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?
为什么要限制a = 1的情况?
Why are you restricting yourself to the case where a = 1?
这篇关于主方法中的ArrayIndexOutOfBounds异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文