I have this equation 2x ^ 2 + 7x-1 which by means of a regex removes what are the following characters: [x], [x ^ n]. to be able to solve them by means of of the general formula.
This is my next code
public void resolver(String msg) throws IOException {
if(!msg.matches("^(?:([+-]?\d+|)x\^[0-9])?(?:([+-]?\d+)x)?([+-]?\d+)?$")){
msg.trim();
System.out.println("No es una ecuación cuadrática");
System.exit(1);
} else {
// System.out.println(msg);
}
String[] lista = new String[3];
Pattern p = Pattern.compile("^(?:([+-]?[0-9]+?|)x\^2)?(?:([+-]?\d+)x)?([+-]?\d+)?$");
Matcher m = p.matcher(msg);
while (m.find()){
lista[0] = m.group(1);
lista[1] = m.group(2);
lista[2] = m.group(3);
}
if(lista[0].isEmpty()){
lista[0] = "1";
}
String a = lista[0];
String b = lista[1];
String c = lista[2];
Double a1 = Double.valueOf(a);
Double b1 = Double.valueOf(b);
Double c1 = Double.valueOf(c);
System.out.println(a1+" "+b1+""+" "+c1);
// Double p1 = ((b1*b1)-(4*(a1*c1)));
Double p2 = Math.sqrt((b1*b1)-(4*(a1*c1)));
// System.out.println(p1);
if(p2 <= 0){
System.out.println("Raiz Imaginaria. No se puede Resolver");
} else {
x1 = (-b1 + p2) / (2*a1);
x2 = (-b1 - p2) / (2*a1);
System.out.println("X1 = " + " "+ x1);
System.out.println("X2 = " + " "+ x2);
String mensaje2 = "\n"+"X1 = "+x1+"\n"+"X2"+" "+x2;
The problem is that when someone puts a negative sign on the operation for example -x ^ 2 + 7x-1, the program takes it as if it were not a regular expression given to the validations.
Edit : Sorry, it does not appear as such an error, but in the regular expression does not recognize the equation if there is no number after the sign "-" and before "x ^ 2"