Hello everyone,
I am having trouble with my program its solving expressions and when I compile it I get a "Illegal start of expresson" line in my output. I am using Jgrasp as my softwear. May I ask to reveiw my code and see on what I did wrong? I am asking for learning purposes.
Thank You.
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Integer.*;
import static java.lang.System.*;
public class ExpressionSolver
{
int answer;
String expString;
ArrayList<String> exp;
public ExpressionSolver(String s)
{
setExpression(s);
}
public void setExpression(String s)
{
expString = s;
exp = new ArrayList<String>();
for(String temp: s.split(" "))
{
exp.add(temp);
}
}
public void solveExpression()
{
int index1, index2, num1, num2;
while(exp.contains(" ") || exp.contains("/"))
{
index1 = exp.indexOf("*");
index2 = exp.indexOf("/");
if(index1 <= 0)
{
index1 = 100;
}
if (index2 <= 0)
{
index2 = 100;
}
if(index1 < index2)
{
num1 = Integer.parseInt(exp.get(index1-1));
num2 = Integer.parseInt(exp.get(index1+1));
answer = num1 * num2;
exp.remove(index1 - 1);
exp.remove(index1 - 1);
exp.set(index1 - 1, Integer.toString(answer));
}
else if(index2 < index1)
{
num1 = Integer.parseInt(exp.get(index2 - 1));
num2 = Integer.parseInt(exp.get(index2 + 1));
answer = num1 / num2;
exp.remove(index2 -1);
exp.remove(index2 - 1);
exp.set(index1 -1 ,Integer.toString(answer));
while(exp.contains("+") || exp.contains("-"))
{
index1 = exp.indexOf("+");
index2 = exp.indexOf("-");
if(index1 <= 0)
{
index1 = 100;
}
if(index2 <= 0)
{
index2 = 100;
}
if(index2 < index1)
{
num1 = Integer.parseInt(exp.get(index1-1));
num2 = Integer.parseInt(exp.get(index1+1));
answer = num1 + num2;
exp.remove(index1 - 1);
exp.remove(index1 - 1);
exp.set(index1 - 1, Integer.toString(answer));
}
else if(index2 < index1)
{
num1 = Integer.parseInt(exp.get(index2 - 1));
num2 = Integer.parseInt(exp.get(index2 + 1));
answer = num1 - num2;
exp.remove(index2 - 1);
exp.remove(index2 - 1);
exp.set(index1 -1 ,Integer.toString(answer));
}
}
}
public String toString()
{
return expString + " = " + answer;
}
}
// My runner class
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Integer.*;
import static java.lang.System.*;
public class ExpressionSolverRunner
{
public static void main( String args[] )
{
ExpressionSolver test = new ExpressionSolver("15 / 3 + 2");
test.solveExpression();
System.out.println(test);
}
}
//My output message
----jGRASP exec: javac -g ExpressionSolver.java
ExpressionSolver.java:108: error: illegal start of expression
public String toString()
^
ExpressionSolver.java:108: error: ';' expected
public String toString()
^
ExpressionSolver.java:112: error: reached end of file while parsing
}
^
3 errors
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.