0

This is a question for school, I need to write a method to find real roots. My program currently works but now I need to return the two roots as arrays, and generalize it so when a is equals to 0 the method should return an array holding one element, holding -c/b, and if a=b=c=0 my method should throw an exception.

public class Quadratic {

    public static void main(String args[]) {
        Quadratic obj = new Quadratic();
        int a = 1, b = -6, c = 12;
        obj.findRoots(a, b, c);
    }

    public void findRoots(int a, int b, int c) {
        // If a is 0, then equation is not
        // quadratic, but linear

        if (a == 0) {
            throw new IllegalArgumentException("a = 0");
        }

        int d = b * b - 4 * a * c;
        double sqrt_val = sqrt(abs(d));

        if (d > 0) {
            System.out.println("Roots are real and different \n");

            System.out.println((double) (-b + sqrt_val) / (2 * a) + "\n" + (double) (-b - sqrt_val) / (2 * a));
        } else {
            return;
        }



    }
}

Can I simply convert the variables to arrays? We just started on an array chapter and I have to idea how to go about this.

someone
  • 122
  • 2
  • 9

1 Answers1

0

just store the result to array.

double root[2]={0.0,0.0};
root[0]=(-b + sqrt_val) / (2 * a);
root[1]=(-b - sqrt_val) / (2 * a);

then return it!

public double[] findRoots(int a, int b, int c){

...

return root;
}
someone
  • 122
  • 2
  • 9