0

I'am working on Calculator application.

I've got Class CalcLogic, which handle all logic in App:

public class CalcLogic {

    private CharacterStack characterStack;
    private DigitStack digitStack;
    private StringStack stringStack;


    public CalcLogic() {
        characterStack = new CharacterStack();
        digitStack = new DigitStack();
        stringStack = new StringStack();
    }

    
    public void convertString(String s) {
        String[] arr = s.split("");


        for (int i = 0; i < arr.length; i++) {
            stringStack.push(arr[i]);
        }

        while (!stringStack.isEmpty()) {
            if ((!stringStack.isEmpty()) && stringStack.peek().matches("[0-9]+")) {
                digitStack.push(Double.valueOf(stringStack.pop()));
            }
            if ((!stringStack.isEmpty()) && stringStack.peek().matches("[(+=\\-*/^)]+")) {
                characterStack.push(stringStack.pop());
            }
        }
        
        System.out.println(digitStack);
        System.out.println(characterStack);
    }

}

Got MainApp:

 public static void main(String[] args) {
        CalcLogic calcLogic = new CalcLogic();
        calcLogic.convertString(new String("1+2*(3+4/2-(1+2))*2+1"));
    }
}

problem is in converting digits:

 if ((!stringStack.isEmpty()) && stringStack.peek().matches("[0-9]+")) {
            digitStack.push(Double.valueOf(stringStack.pop()));
  }

digits from String:

String s = "1+2*3(30+4/2-(10+2))*2+1";

will be pushed in digitStack like this:

1.0 2.0 2.0 1.0 2.0 4.0 [0.0 3.0] 2.0 1.0

because it convert every single element from String separate.

expected output in digitStack should be:

1.0 2.0 2.0 1.0 2.0 4.0 30.0 2.0 1.0

How can I achive it?

Dartweiler
  • 85
  • 8
  • The problem coms from `String[] arr = str.split("");` it split character by character – ibra Nov 09 '20 at 12:47

1 Answers1

1

The problem coms from String[] arr = str.split(""); it split character by character.
you can check it with this code

        String str = "1+2*(3+4/2-(1+2))*2+1";
        String[] arr = str.split("");
        
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

for the solution on how you should split a mathematical expression using java, look at this stackoverflow entry: java-splitting-with-math-expression which is :

String[] arr = str.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");

for the details on the split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)") please go read the stackoverflow entry: java-splitting-with-math-expression
good luck.

ibra
  • 1,164
  • 1
  • 11
  • 26