The goal is to create a program that takes a quadratic equation in quadratic form and solve it. Is there a different way to go about doing so other than StringTokenizer? Or is it possible to isolate just ^2 in StringTokenizer rather than ^ and 2 like it is doing now? I realized that using the way I wrote it, it will not allow equations to use 2 at all.
This question requires me to not take individual coefficients, but rather the entire equation itself.
Sample run: ”java SolveEquation2 1.5625x∧2+2.5x+1=0”. For this input the output should be: ”x=-0.8”
import java.util.Scanner;
import java.util.StringTokenizer;
class SolveEquation2 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Input a quadratic");
String equation = scan.nextLine();
StringTokenizer st = new StringTokenizer(equation, "x^2+-");
String a,b,c;
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
double c1 = Double.parseDouble(c);
double x = (b1 * b1) - (4 * a1 * c1);
double var1 = (-b1 + Math.sqrt(x)) / (2*a1);
double var2 = (-b1 - Math.sqrt(x)) / (2*a1);
if (x == 0){
System.out.println("x = " + var1);
}
if (x > 0){
System.out.println("x1 = " + var1);
System.out.println("x2 = " + var2);
}
if (x < 0){
System.out.println("No Solution");
}
}
}