Convert arithmetic string into double in Java -
i have program user inputs 6 doubles, , program outputs every combination of operators can go in-between doubles 1024 separate strings. here first 2 results if user inputed 14,17,200,1,5, , 118:
"14.0+17.0+200.0+1.0+5.0+118.0" "14.0+17.0+200.0+1.0+5.0-118.0"
what want perform arithmetic according order of operations. each double stored variable through f , each operator in-between these variables stored char a_b through e_f. so:
double a, b, c, d, e, f; char a_b, b_c, c_d, d_e, e_f;
my first thought write code this:
public double operategroup() { value = 0; switch (a_b) { case '+': value += + b; break; case '-': value += - b; break; case '*': value += * b; break; case '/': value += / b; break; default: break; } switch (b_c) { case '+': value += c; break; case '-': value += -c; break; case '*': value *= c; break; case '/': value /= c; break; default: break; } switch (c_d) { case '+': value += d; break; case '-': value += -d; break; case '*': value *= d; break; case '/': value /= d; break; default: break; } switch (d_e) { case '+': value += e; break; case '-': value += -e; break; case '*': value *= e; break; case '/': value /= e; break; default: break; } switch (e_f) { case '+': value += f; break; case '-': value += -f; break; case '*': value *= f; break; case '/': value /= f; break; default: break; } return value; }
but doesn't work because same doing (a o b) o c) o d) o e) o arbitrary operator. tips?
if need operators' , operands' information, should build parse tree (this has been asked before).
if interested in result, can evaluate string
directly:
import javax.script.scriptenginemanager; import javax.script.scriptengine; public class eval { public static void main(string[] args) throws exception { scriptenginemanager s = new scriptenginemanager(); scriptengine engine = s.getenginebyname("javascript"); string exp = "14.0+17.0+200.0+1.0+5.0-118.0"; system.out.println(engine.eval(exp)); } }
output:
119.0
Comments
Post a Comment