ArrayIndexOutOfBounds exception in main method

后端 未结 4 1247
不思量自难忘°
不思量自难忘° 2021-01-25 18:53

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         


        
4条回答
  •  一个人的身影
    2021-01-25 19:17

    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?

提交回复
热议问题