Help With Expression Solver
I am trying to create a program that takes string expressions and solves them mathematically (i.e. string "5 + 4 * 2" will evaluate as 13). i have this much of the program made, but I am not sure why it is not working. it keeps telling me there is a "Number Format Exception"
Please help!
import java.util.ArrayList;
import java.util.Scanner;
importstatic java.lang.Integer.*;
importstatic java.lang.System.*;
import java.lang.*;
class ExpSolver
{
private ArrayList<String> list;
private String expression;
private String trimmedExp;
private String evaluated;
privateint eval;
public ExpSolver(String s)
{
list=new ArrayList<String>();
expression=s;
trimmedExp=s.trim();
for (int x=0; x<trimmedExp.length(); x++)
{
list.add(""+trimmedExp.charAt(x));
}
}
publicvoid setExpression(String s)
{
expression=s;
trimmedExp=s.trim();
list.clear();
for (int x=0; x><trimmedExp.length(); x++)
{
list.add(""+trimmedExp.charAt(x));
}
}
publicvoid solveExpression()
{
eval=0;
for (int x=0; x><list.size(); x++)
{
if (list.get(x).equals("*")||list.get(x).equals("/"))
{
if (list.get(x).equals("*"))
{
list.set(x-1, String.valueOf(Integer.parseInt(list.get(x-1))*Integer.parseInt(list.get(x+1))));
list.remove(x+1);
list.remove(x);
}
elseif(list.get(x).equals("/"))
{
list.set(x-1, String.valueOf(Integer.parseInt(list.get(x-1))/Integer.parseInt(list.get(x+1))));
list.remove(x+1);
list.remove(x);
}
}
}
for (int x=0; x><list.size(); x++)
{
if (list.get(x).equals("-"))
{
list.set(x-1, String.valueOf(Integer.parseInt(list.get(x-1))-Integer.parseInt(list.get(x+1))));
list.remove(x);
list.remove(x+1);
}
elseif (list.get(x).equals("+"))
{
list.remove(x);
}
}
for (int x=0; x><list.size(); x++)
{
if (list.get(x).equals(" "))
{
list.remove(x);
}
list.set(x, list.get(x).trim());
}
for (int x=0; x><list.size(); x++)
{
eval+=Integer.parseInt(list.get(x));
}
evaluated=String.valueOf(eval);
}
public String toString( )
{
return evaluated;
}
}
publicclass Lab04b
{
publicstaticvoid main( String args[] )
{
ExpSolver test =new ExpSolver("3 + 5");
test.solveExpression();
out.println(test.toString());
test.setExpression("3 * 5");
test.solveExpression();
out.println(test);
test.setExpression("3 - 5");
test.solveExpression();
out.println(test);
test.setExpression("3 / 5");
test.solveExpression();
out.println(test);
test.setExpression("5 * 5 + 2 / 2 - 8 + 5 * 5 - 2");
test.solveExpression();
out.println(test);
}
}
>

