-2

I'm extremely new to java and I was asked to program a quadratic equation solver for a class in school. I'm not sure if my code is even remotely correct, but I get the output "NaN" for whatever input I give.

import javax.swing.JOptionPane;
import static java.lang.Math.sqrt;

public class FunTest
{
    public static void main(String[] args)
    {
      String number1=JOptionPane.showInputDialog("Enter A");
      int a=Integer.parseInt(number1);

      String number2=JOptionPane.showInputDialog("Enter B.");
      int b=Integer.parseInt(number2);

      String number3=JOptionPane.showInputDialog("Enter C.");
      int c=Integer.parseInt(number3);

      double discriminantsquared=((b^2)-(4*a*c));
      double discriminant=Math.sqrt(discriminantsquared);

      double x1=(((b*-1)+discriminant)/(2*a));
      double x2=(((b*-1)-discriminant)/(2*a));

      String output=("x1= "+x1+"\n"+"x2= "+x2);
      JOptionPane.showMessageDialog(null, output);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bilal
  • 19
  • 1
    *I'm not sure if my code is even remotely correct*. Then why would you be surprised by any output? And what is your question exactly? – shmosel Aug 31 '17 at 05:37
  • Have you stepped through the code in your IDE debugger? Please do at least that before asking here so you can at least pinpoint where the problem is. – Jim Garrison Aug 31 '17 at 05:37
  • 1
    You say you're new to Java, but perhaps you've had experience in other languages? Please be aware that the "power" operator is one that changes from language to language. Some languages use `^`, some languages use `**`, and Java doesn't have an operator. – ajb Aug 31 '17 at 05:44
  • Once you fix the obvious bug identified by @Murelnik you still have to add some code to deal with quadratics that have no roots (i.e. `discriminantsquared < 0`) – Jim Garrison Aug 31 '17 at 05:45

1 Answers1

4

b^2 is not "b to the power of two", it is "b xored with 2". For power you could use Math.pow(b, 2), or simply b * b.

Mureinik
  • 297,002
  • 52
  • 306
  • 350