John John - 5 months ago 10
Java Question

Operation priority

I wrote the code of a calculator, but it's not respecting the priority of operation. what i need to change?

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

c = sc.nextInt();

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

a = sc.nextInt();
switch (semn) {
case '+' : c += a; break;
case '-' : c -= a; break;
case '*' : c *= a; break;
case '/' : c /= a; break;
}
}while(semn!='=');
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);
    }
}
Comments