Sorin Circa
Sorin Circa

Reputation: 9

Expression Solver Algorithm with Java

I am trying to create a program that will take in an expression as a String and solve it. So if the input is 3 + 5 it would return 8. I have done majority of the coding, but I'm not sure why I keep getting an UnsupportedOperationExpression in Java. Please help if you can!

** Also I have to use ArrayLists on this assignment because I have not yet learned lists. Here is my current code so far:

    import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class FirstPart {
   public static void main(String[] args) {
      String sampleString = "1 + 2 + 3 / 2 + 1";
      String[] items = sampleString.split(" ");
      List<String> itemList = Arrays.asList(items);
      System.out.println(itemList);
      for(int zz=0; zz<itemList.size(); zz++)
        if(itemList.get(zz).equals("*"))
           {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))*Integer.parseInt(itemList.get(zz+1)))));
           itemList.remove(zz+1);
           itemList.remove(zz);
           zz--;}
        else if(itemList.get(zz).equals("/"))
           {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))/Integer.parseInt(itemList.get(zz+1)))));
           itemList.remove(zz+1);
           itemList.remove(zz);
           zz--;}
      for(int zz=0; zz<itemList.size(); zz++)
        if(itemList.get(zz).equals("+"))
           {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))+Integer.parseInt(itemList.get(zz+1)))));
           itemList.remove(zz+1);
           itemList.remove(zz);
           zz--;}
        else if(itemList.get(zz).equals("-"))
           {itemList.set(zz-1,Integer.toString((Integer.parseInt(itemList.get(zz-1))+Integer.parseInt(itemList.get(zz+1)))));
           itemList.remove(zz+1);
           itemList.remove(zz);
           zz--;}
      System.out.println(itemList);
   }
   }

Thanks again if you can help!

Upvotes: -1

Views: 2559

Answers (2)

alkurmtl
alkurmtl

Reputation: 149

Try reading about reverse polish notation algorithm. It seems to do exactly what you need, you only have to implement it.

https://en.wikipedia.org/wiki/Reverse_Polish_notation

Upvotes: 1

wero
wero

Reputation: 32980

If you construct a List from an array like this

List<String> itemList = Arrays.asList(items)

the returned list does not allow to remove an item from the list

itemList.remove(zz + 1); // throws java.lang.UnsupportedOperationException

Instead, create an empty list which supports removal and add all the array elements to it:

List<String> itemList = new java.util.ArrayList<>();
java.util.Collections.addAll(itemList, items);

Upvotes: 3

Related Questions