您可以使用以下代码。首先,它会检查输入方程是否是二次的。如果输入方程是二次的,那么它将找到根。此代码也能够找到复杂的根。
公共静态无效主要(字符串[]参数){
// Declaration of variables
float a = 0, b = 0, c = 0, disc, sq_dis;
float[] root = new float[2];
StringBuffer number;
Scanner scan = new Scanner(System.in);
// Input equation from user
System.out.println("Enter Equation in form of ax2+bx+c");
String equation = scan.nextLine();
// Regex for quadratic equation
Pattern quadPattern = Pattern.compile("(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*");
Matcher quadMatcher = quadPattern.matcher(equation);
scan.close();
// Checking if given equation is quadratic or not
if (!(quadMatcher.matches())) {
System.out.println("Not a quadratic equation");
}
// If input equation is quadratic find roots
else {
// Splitting equation on basis of sign
String[] array = equation.split("(?=[+-])");
for (String term : array) {
int len = term.length();
StringBuffer newTerm = new StringBuffer(term);
// If term ends with x2, then delete x2 and convert remaining term into integer
if (term.endsWith("X2") || (term.endsWith("x2"))) {
number = newTerm.delete(len - 2, len);
a += Integer.parseInt(number.toString());
}
// If term ends with x, then delete x and convert remaining term into integer
else if (term.endsWith("X") || (term.endsWith("x"))) {
number = newTerm.deleteCharAt(len - 1);
b += Integer.parseInt(number.toString());
}
// If constant,then convert it into integer
else {
c += Integer.parseInt(term);
}
}
// Display value of a,b,c and complete equation
System.out.println("Coefficient of x2: " + a);
System.out.println("Coefficient of x: " + b);
System.out.println("Constent term: " + c);
System.out.println("The given equation is: " + a + "x2+(" + b + ")x+(" + c + ")=0");
// Calculate discriminant
disc = (b * b) - (4 * a * c);
System.out.println(" Discriminant= " + disc);
// square root of discriminant
sq_dis = (float) Math.sqrt(Math.abs(disc));
// conditions to find roots
if (disc > 0) {
root[0] = (-b + sq_dis) / (2 * a);
root[1] = (-b - sq_dis) / (2 * a);
System.out.println("Roots are real and unequal");
System.out.println("Root1= " + root[0]);
System.out.println("Root2= " + root[1]);
}
else if (disc == 0) {
root[0] = ((-b) / (2 * a));
System.out.println("Roots are real and equal");
System.out.println("Root1=Root2= " + root[0]);
}
else {
root[0] = -b / (2 * a);
root[1] = Math.abs((sq_dis) / (2 * a));
System.out.println("Roots are complex");
System.out.println("ROOT1= " + root[0] + "+" + root[1] + "+i");
System.out.println("ROOT2= " + root[0] + "-" + root[1] + "+i");
}
}