Andrew Andrew - 13 days ago 6
Java Question

Simple calculator wich respect operation priority

I wrote the code of a calculator, but it's not respecting the priority of operation. What i need to change? The program doese't have to support

()
.
When you run it, you should enter a number, then a sign and continue reading numbers and signes utill user input is
=
.

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a,c ;
char sgn;

c = sc.nextInt();

do{
sgn = sc.next().charAt(0);
if (sgn=='=') break;

a = sc.nextInt();
switch (sgn) {
case '+' : c += a; break;
case '-' : c -= a; break;
case '*' : c *= a; break;
case '/' : c /= a; break;
}
}while(sgn!='=');
System.out.println(c);
}
}

Answer

Ok, solved by myself

Scanner sc = new Scanner(System.in);

    int nr = sc.nextInt(); 

    for (int i = 0; i < nr; i++) {
        int prod = sc.nextInt();
        int sum = 0;
        char ops;

        do {
            ops = sc.next().charAt(0);
            switch (ops) {
            case '*':
                prod *= sc.nextInt();
                break;
            case '/':
                prod /= sc.nextInt();
                break;
            case '+':
                sum += prod;
                prod = sc.nextInt();
                break;
            case '-':
                sum += prod;
                prod = -sc.nextInt();
                break;
            }
        } while (ops != '=');

        System.out.println(sum + prod);
    }
}