Here you go, hope this helps ...
The code that you are about to see can solve all the basic equations, which means that it can solve the equations in which it only contains . , + , - , * and / or / in the equation. This equation can also add, subtract, multiply and / or divide decimal numbers. This one cannot solve equations containing x^y , (x) , [x] , etc.
public static boolean isNum(String e) { String[] num=new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}; boolean ret=false; for (String n : num) { if (e.contains(n)) { ret=true; break; } } return ret; } public static boolean ifMax(String[] e, int i) { boolean ret=false; if (i == (e.length - 1)) { ret=true; } return ret; } public static String getResult(String equation) { String[] e=equation.split(" "); String[] sign=new String[] {"+", "-", "*", "/"}; double answer=Double.parseDouble(e[0]); for (int i=1; i<e.length; i++) { if (isNum(e[i]) != true) { if (e[i].equals(sign[0])) { double cc=0; if (ifMax(e, i) == false) { cc=Double.parseDouble(e[i+1]); } answer=answer+(cc); } else if (e[i].equals(sign[1])) { double cc=0; if (ifMax(e, i) == false) { cc=Double.parseDouble(e[i+1]); } answer=answer-(cc); } else if (e[i].equals(sign[2])) { if (ifMax(e, i) == false) { answer=answer*(Double.parseDouble(e[i+1])); } } else if (e[i].equals(sign[3])) { if (ifMax(e, i) == false) { answer=answer/(Double.parseDouble(e[i+1])); } } } } return equation+" = "+answer; }
And here is an example of this:
Input:
System.out.println(getResult("1 + 2 + 3 + 4 / 2 - 3 * 6"));
Output:
1 + 2 + 3 + 4 / 2 - 3 * 6 = 12
Shae noble
source share