ZeldaX ZeldaX - 1 year ago 89
Java Question

String to Integer Expressions

I am trying to convert an expression given as a String into an Integer. For ex. if given "1+5*5" the method should return "26". I started writing the code only for solving a multiplication, however, when I run it there is not an output

public static void operationS(ArrayList<String> m)
for (int i=0; i<m.size(); i++)
while ( (m.get(i)).contains("*"))
int x = ((m.get(i)).indexOf("*"));
char A=((m.get(i)).charAt(x-1));
char B= ((m.get(i)).charAt(x+1));

int r= Character.getNumericValue(A)*Character.getNumericValue(B);

String numberAsString = Integer.toString(r);

if(x==1 && (m.get(i)).length()==3)
m.set(i, numberAsString);


if(x==1 && (m.get(i)).length()>3)
String n = numberAsString+((m.get(i)).substring(x+2));
m.set(i, n);


String k= ((m.get(i)).substring(0,x-1))+numberAsString+((m.get(i)).substring(x+2));

for (int u=0;u<m.size();u++)
System.out.println (m.get(u));

Since I cannot import any libraries, my plan of action was replacing the String every time an operation was completed.

I plan on using the same loop for adding, subtracting and dividing

Answer Source

Consider parsing your expression. You can probably use an Prefix, Infix, or Postfix notation and parsing to evaluate the input expression.

I came across an article that can help you in understanding how to achieve this:


The article basically talks about different approaches to solve this problem.

I personally liked the recursive approach. So if you understand recursion, you can choose that.

But if you have a requirement to use only a loop, you may prefer one of the other approaches.

Update: Adding a sample piece of code implementing recursion based on the article linked above.

    static final char[] ops = { '-', '+', '*', '/'};

    static double evaluate(String s){
        for(char op: ops) {
                String op1 = s.substring(0, s.indexOf(op));
                String op2 = s.substring(s.indexOf(op) + 1, s.length());
                switch(op) {
                    case '-': return evaluate(op1) - evaluate(op2);
                    case '+': return evaluate(op1) + evaluate(op2);
                    case '*': return evaluate(op1) * evaluate(op2);
                    case '/': return evaluate(op1) / evaluate(op2);
        /* at this point there is no operator in the term anymore, just a number */
        return (convertToDouble(s));

    private static double convertToDouble(String s) {
        return Double.parseDouble(s);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download