aybkcn
aybkcn

Reputation: 25

String Calculator in Java

I want to create a string calculator and this is my full of code. Output should be 24 (order of operation will be as in string) but output is 3. What should I do?

public class Örnek{

     public static void main(String[] args)
     {
         String a = "2+5*3+1";
            System.out.println(a);
            String operators[]=a.split("[0-9]");
            String operands[]=a.split("[*+-/]");
            int agregate = Integer.parseInt(operands[0]);
            for(int i=1;i<operands.length-1;i++){
                if(operators[i].equals("+"))
                    agregate += Integer.parseInt(operands[i]);
                else if(operators[i].equals("-"))
                    agregate -= Integer.parseInt(operands[i]);
                if(operators[i].equals("*"))
                    agregate *= Integer.parseInt(operands[i]);
                else 
                    agregate /= Integer.parseInt(operands[i]);
            }

            System.out.println(agregate);
     }

}

Upvotes: 0

Views: 2378

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201527

You are missing an else on the third condition, and you need a second index variable for your operand array. Changing it like

int agregate = Integer.parseInt(operands[0]);
int o = 1;
for (int i = 0; i < operators.length; i++) {
    if (operators[i].equals("+"))
        agregate += Integer.parseInt(operands[o++]);
    else if (operators[i].equals("-"))
        agregate -= Integer.parseInt(operands[o++]);
    else if (operators[i].equals("*"))
        agregate *= Integer.parseInt(operands[o++]);
    else if (operators[i].equals("/"))
        agregate /= Integer.parseInt(operands[o++]);
}

System.out.println(agregate);

Gives

22

Which is how I read your String left-to-right. 2+5 is seven, 7*3 is twenty-one and 21+1 is twenty-two.

Upvotes: 0

corsiKa
corsiKa

Reputation: 82589

You appear to be missing an else missing on the third one which means the divide is always firing any time you don't have a multiply.

Upvotes: 2

Related Questions