Although the program works perfectly fine, my professor mentioned that the following is a logical error and should be fixed. I’m stumped, isn’t there only one root when the discriminant is equal to 0? Help will truly be appreciated!
This is the code he mentioned:
if(discrim == 0)
{
eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);
System.out.println("This equation only has a single real root. Root = " + eq1root1);
Here’s the full code:
import java.lang.Math;
import javax.swing.JOptionPane;
public class Assignment6
{
public static void main(String[] args)
{
String a,
b,
c;
double coefA,
coefB,
coefC,
discrim,
eq1root1,
eq1root2;
//Here the user is inputting the coefficients through a popup dialog box
//Then the entered Strings are being converted to floating point numbers.
a = JOptionPane.showInputDialog( "Please enter a number for the quadratic coefficient a" );
coefA = Double.parseDouble (a);
b = JOptionPane.showInputDialog( "Please enter a number for the quadratic coefficient b" );
coefB = Double.parseDouble (b);
c = JOptionPane.showInputDialog( "Please enter a number for the quadratic coefficient c" );
coefC = Double.parseDouble (c);
//Here the coefficients that the user entered are being displayed.
System.out.println("Your coefficient a = " + coefA);
System.out.println("Your coefficient b = " + coefB);
System.out.println("Your coefficient c = " + coefC);
//The following "nested if" statement sorts out equations with only 1 root, 2 roots, and or no roots at all.
discrim = coefB*coefB - (4 * coefA * coefC);
if(discrim == 0)
{ eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);
System.out.println("This equation only has a single real root. Root = " + eq1root1);
}
else if (discrim > 0)
{ eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);
eq1root2 =((-1*coefB) - Math.sqrt(discrim))/(2 * coefA);
System.out.println("This equation has two real roots.");
System.out.println("Root 1 = " + eq1root1);
System.out.println("Root 2 = " + eq1root2);
}
else
{
System.out.println("This equation does not have any real roots.");
}
}
}
Only error I can see is that you don’t really need to do:
You can do only
Since you’re inside the if where you know the descriminant is zero.
Like mentioned in another comment, you need to make sure that coefA is different from 0, since that will cause your code to raise an exception (you can’t divide by 0). Although that wouldn’t actually be a quadratic equation, it’s important to validate it.