Basically, I'm trying to make a Simplifier that can take inputs in the form of a String
and print out the solution step-by-step. Now that I've got it working, I think it has some cleanliness issues.
public static void test(String eqn) {
char[] order = { '^', '*', '/', '+'}; //order of precendece
int found, i, j;
eqn = eqn.replace("-", "+-"); //Subtracting = Adding (-)ve number.
eqn = eqn.replace(" ", ""); //Spaces can cause a lot of trouble.
String eqnC, left, right;
System.out.println("=>\t"+eqn);
for(char op : order) {
while ((found = eqn.indexOf(op)) > -1) {
left = eqn.substring(0, found);
right = eqn.substring(found + 1);
//keep 'walking' up and down the String till a non-number encoutered.
for( i = left.length() - 1; i >= 0; i--)
if(!isPONumber(left.charAt(i)))
break;
for( j = 0; j < right.length(); j++)
if(!isPONumber(right.charAt(j)))
break;
double lV = Double.parseDouble(left.substring(++i)); //left operand
double rV = Double.parseDouble(right.substring(0, j)); //right operand
eqn = left.substring(0, i) + putV(lV, rV, op) + right.substring(j);
System.out.println("=\t" + eqn);
}
}
}
private static String putV(double a, double b, char op) {
switch(op) {
case '^': return Math.pow(a, b) + "";
case '/': return (a / b) + "";
case '*': return (a * b) + "";
case '+': return (a + b) + "";
}
return null;
}
/*
* Limit (for now) : decimal support.
*/
private static boolean isPONumber(char c) {
return Character.isDigit(c) || c == '.' || c == '-';
}
Here are some outputs:
=> 2*84/6+7^2
= 2*84/6+49.0
= 168.0/6+49.0
= 28.0+49.0
= 77.0
=> 3^3/3^2
= 27.0/3^2
= 27.0/9.0
= 3.0
=> 400^0.5
= 20.0
I'd be grateful if anyone would comment and criticize and help me to clean-up my code. I also invite suggestions for making it better, improvising it and so on.