hola para todos aquellos que se preguntan como crear su propio evaluador de expresiones del tipo 5*4 +3 -2 *(5) a qui les tengo un pequeño ejemplito
en menos de 81 lineas y sin usar regex
package javaapplication17;
import java.util.HashMap;
public class Interpreter {
private final HashMap<String, String> variables = new HashMap<>();
public static void main
(String[] args
) { Interpreter interpreter = new Interpreter();
//calculation
"1",
"12",
"5^2",
"12+13",
"4+2-1",
"(1)",
"(4/2+1*2)",
"(1+3)+(5+6-3+13)",
"3*(4+2)",
"3*4*(5+3)+16+2",
"8*7+(4+3+6*(5+4))",}) {
System.
out.
println("text= " + text
+ " " + interpreter.
evalProgram(text
)); }
//programing feature booleans
System.
out.
println("booleans"); "1<2",
"2>3",
"12>13",
"12<14",
"(5+1)<14",
"14<(5+1)",
"(1+2)-3<4*2",
"true",
"false",
"false&true",
"false&true",
"false&true|true",
"true&false|true",
"1+2<3&4<2|false",
"(1+2)*3-1<4|false&true|(3+1)<4"}) {
Interpreter programEvaluetor = new Interpreter();
final String evalBoolean
= programEvaluetor.
evalProgram(text
); System.
out.
println(text
+ " = " + evalBoolean
); }
//simple scripts
System.
out.
println("programs"); "1",
"3+2-1",
"3+2-1\n1+2+1",
"4*5\n5*3",
"5*8\n4+2\n5+5+5",
"a=3*4\na",
"b=3*4\nb",
"abc=3*4\nabc\ncde=2*5+1\ncde",
"a=2\nb=3\nc=a+b\nc",
"c=true\nc",}) {
Interpreter programEvaluetor = new Interpreter();
System.
out.
println("=======program================================"); System.
out.
println("=======endprogram============================="); System.
out.
println("=======output program========================="); System.
out.
println(programEvaluetor.
evalProgram(text
)); System.
out.
println("=======end output program====================="); }
//conditionals programs
System.
out.
println("conditionals programs"); "1\nif(true){\n2\n}",
"if(false){\n1\n}",
"2\nif(true){\n1\n}",
"2\nif(false){\n1\n}\n3",
"1\nif(true){\n2\n}\n3",}) {
Interpreter programEvaluetor = new Interpreter();
System.
out.
println("=======program================================"); System.
out.
println("=======endprogram============================="); System.
out.
println("=======output program========================="); System.
out.
println(programEvaluetor.
evalProgram(text
)); System.
out.
println("=======end output program====================="); }
//conditionals programs
}
private boolean evalCondition
(String condition
) { final String evalBoleanExpresion
= evalBoleanExpresion
(condition.
substring(3, condition.
length() - 2)); return Boolean.
parseBoolean(evalBoleanExpresion
); }
String[] comands
= expresion.
split("\n"); boolean run = true;
for (int i = 0; i < comands.length; i++) {
if (comand.startsWith("if")) {
run = evalCondition(comand);
continue;
}
if (comand.startsWith("}")) {
run = true;
continue;
}
if (run) {
final String evalComand
= evalComand
(comand
); if (!evalComand.isEmpty()) {
result += evalComand + "\n";
}
}
}
return result.isEmpty() ? "" : result.substring(0, result.length() - 1);
}
String[] comandPart
= expresion.
split("=");
if (comandPart.length == 1) {
String candidate
= comandPart
[0]; if (candidate.equals("true") || candidate.equals("false")) {
return eval(expresion);
}
if (candidate.
chars().
allMatch(Character::isLetter
)) { return "" + variables.get(candidate);
}
return eval(expresion);
}
if (comandPart.length == 2) {
variables.put(comandPart[0], (eval(comandPart[1])));
return "";
}
return result;
}
int beginIndex = -1;
for (int i = 0; i < inputString.length(); i++) {
final char character = inputString.charAt(i);
if (character == '(') {
beginIndex = i;
buffer = "";
buffer += character;
}
if (!buffer.isEmpty()) {
String charLetter
= (character
+ ""); buffer += charLetter.equals("(") || charLetter.equals(")") ? "" : charLetter;
}
if (character == ')') {
buffer += character;
inputString = inputString.substring(0, beginIndex) + evalParentesis(buffer) + inputString.substring(beginIndex + buffer.length());
i = 0;
buffer = "";
}
}
return "" + evalExpresion(inputString);
}
return evalExpresion(coeficientString.substring(1, coeficientString.length() - 1));
}
if (expresion.contains("<")
|| expresion.contains(">")
|| expresion.contains("&")
|| expresion.contains("|")
|| expresion.contains("true")
|| expresion.contains("false")) {
result = evalBoleanExpresion(expresion);
} else {
result = evalAddExpresion(expresion) + "";
}
return result;
}
private int evalAddExpresion
(String expresion
) { char[] characters = expresion.toCharArray();
int result = 0;
for (int i = 0; i < expresion.length(); i++) {
char character = expresion.charAt(i);
buffer += character;
if (i == characters.length - 1
|| characters[i + 1] == '+'
|| characters[i + 1] == '-') {
if (buffer.startsWith("-")) {
result -= evalSub(buffer.replace("-", ""));
} else {
result += evalSub(buffer.replace("+", ""));
}
buffer = "";
}
}
return result;
}
private int evalSub
(final String expresion
) { char[] characters = expresion.toCharArray();
int result = 1;
for (int i = 0; i < expresion.length(); i++) {
char character = expresion.charAt(i);
buffer += character;
if (i == characters.length - 1
|| characters[i + 1] == '*'
|| characters[i + 1] == '/') {
if (buffer.startsWith("/")) {
result /= evalExpo(buffer.replace("/", ""));
} else {
result *= evalExpo(buffer.replace("*", ""));
}
buffer = "";
}
}
return result;
}
private int evalExpo
(final String expresion
) { char[] characters = expresion.toCharArray();
int result = 1;
for (int i = expresion.length() - 1; i >= 0; i--) {
char character = expresion.charAt(i);
buffer = character + buffer;
if (i == 0 || characters[i - 1] == '^') {
result
= (int) (Math.
pow(Integer.
parseInt(evalElement
(buffer.
replace("^",
""))),
(result
))); buffer = "";
}
}
return result;
}
if (expresion.
chars().
allMatch(Character::isLetter
)) { return variables.get(expresion);
} else {
return expresion;
}
}
char[] characters = expresion.toCharArray();
boolean result = true;
for (int i = 0; i < expresion.length(); i++) {
char character = expresion.charAt(i);
buffer += character;
if (i == characters.length - 1
|| characters[i + 1] == '&'
|| characters[i + 1] == '|') {
if (buffer.startsWith("&")) {
result
&= Boolean.
parseBoolean(evalBooleanElement
(buffer.
replace("&",
""))); } else if (buffer.startsWith("|")) {
result
|= Boolean.
parseBoolean(evalBooleanElement
(buffer.
replace("|",
""))); } else {
result
= Boolean.
parseBoolean(evalBooleanElement
(buffer
)); }
buffer = "";
}
}
return result + "";
}
if (expresion.contains("<") || expresion.contains(">")) {
String[] split
= expresion.
split("<|>"); String left
= evalExpresion
(split
[0]); String right
= evalExpresion
(split
[1]);
if (expresion.contains("<")) {
}
if (expresion.contains(">")) {
}
} else {
result = expresion;
}
return result;
}
}
en un futuro agregare la funcionalidad de de agregar
variables funciones bucles y condicionales para que se paresca a javascript
porfavor cuentenme lo que quieran del post preguntas traumas amensas o respuesta troll pero no me ignoren por que soy una perra de atención
diganme si lo han usado y en que