Suppose a java program which gets a polynomial equation like "3x^2 - 4x^3 + 3x^3" as a string input from user then gets another number as "x" then solve the given equation with given x and print result.
If you have any idea or solution, I would be thankful to hear. thanks a lot!
input:
3x^2 - 4x^3 + 3x^3
x = 4
output:
-16
input:
3x - 4x^2 + 2x^4
x = 2
output:
22
with JDK1.6, you can use the built-in Javascript engine.
For example:
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine engine = m.getEngineByName("JavaScript");
String equation = "3+2";
System.out.println(engine.eval(equation));
Would output 5
Unfortunately, this only handles +, -, *, /, not power (^). So we'll have to do some string editing to make it usable, plus adding our x value.
Assuming our x is 4, we want 3x^2 - 4x^3 + 3x^3 to becomes (3*4*4)-(4*4*4*4)+(3*4*4*4)
Here's a quick string builder function I wrote to clean it up.
public static void main(String[] args) throws ScriptException
{
String equation = "3x^2 - 4x^3 + 3x^3";
int x = 4;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(fixEquation(equation, x)));
}
public static String fixEquation(String equation, int x)
{
StringBuilder sb = new StringBuilder(equation.replaceAll(" ", ""));
StringBuilder fixed = new StringBuilder("(");
StringBuilder temp = new StringBuilder("");
for(int i = 0; i < sb.length(); i++)
{
if(sb.charAt(i)=='^')
{
for(int j = i + 1; j < sb.length(); j++)
{
if(j + 1 == sb.length())
{
temp.append(sb.charAt(j));
for(int k = 0; k < Integer.valueOf(temp.toString()); k++)
fixed.append( "*" + x);
temp.replace(0, temp.length(), "");
i = sb.length();
break;
}
if(sb.charAt(j) == '+' || sb.charAt(j) == '-' )
{
for(int k = 0; k < Integer.valueOf(temp.toString()); k++)
fixed.append( "*" + x);
temp.replace(0, temp.length(), "");
i = j - 1;
break;
}
temp.append(sb.charAt(j));
}
}
else if(sb.charAt(i)=='x' && (i + 1 == sb.length() || sb.charAt(i + 1) != '^'))
{
fixed.append("*"+ x) ;
}
else if(sb.charAt(i)=='x' )
{
fixed.append("") ;
}
else if(sb.charAt(i) == '+' || sb.charAt(i) == '-')
{
fixed.append(")" + sb.charAt(i) + "(");
}
else
fixed.append(sb.charAt(i));
}
fixed.append(")");
return fixed.toString();
}