What is wrong with my code for quadratic formula

45 views Asked by At
public class QuadraticEqn {
private double a, b, c;
public QuadraticEqn(double x, double y, double z){
    a=x;
    b=y;
    c=z;
}
private double disc = b*b-4*a*c;
public boolean hasSolutions(){
    if(disc>=0)
        return true;
    else
        return false;
 }
 public double getSolutions1(){
     return (-b-Math.sqrt(disc))/(2*a);
}
 public double getSolutions2(){
        return (-b+Math.sqrt(disc))/(2*a);
    }

}


import java.util.Scanner;
public class QuadraticEquationTest {

     public static void main(String[] args) {
        Scanner values = new Scanner(System.in);
        System.out.println("enter values for a, b, c:");
        double a=values.nextDouble();
        double b=values.nextDouble();
        double c=values.nextDouble();

        QuadraticEqn qe = new QuadraticEqn(a, b, c);
        if (qe.hasSolutions())
        System.out.println(qe.getSolutions1()+"  "+qe.getSolutions2());
        else
         System.out.println("No real solutions");
    }

}

The main class is supposed to print out real solutions to the given inputs. I have been stuck on this problem for hours. I cant seem to figure out what I did wrong. I keep getting the wrong answers. Help please!

1

There are 1 answers

0
DeadChex On BEST ANSWER

You have an issue with

private double disc = (b*b)-(4*a*c);

Right away when you make a QuadraticEqn the varible disc is given a value, however, it's given a value before you get to save a, b, and c. And so it creates disc as though a, b, and c are each 0.

To fix it, update disc in your constructor.

public class QuadraticEqn {
   private double a, b, c, disc; //We're created before the constructor 
                                 //runs with default values of 0!
   public QuadraticEqn(double x, double y, double z){
       a=x;
       b=y;
       c=z;
       disc = b*b-4*a*c; //Give me a value after we know what the others are!
   }

   public boolean hasSolutions(){
     if(disc>=0)
         return true;
     else
         return false;
   }

   public double getSolutions1(){
      return (-b-Math.sqrt(disc))/(2*a);
   }

   public double getSolutions2(){
      return (-b+Math.sqrt(disc))/(2*a);
   }

}