I wrote the code for a calculator, but it's not respecting the priority of operation. What do 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 signs until 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);
}
}
Ok, solved by myself
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
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);
}