In: Computer Science
In this problem, we will be evaluating simple math expressions that contain numbers, +, *, (, and ). Specifically, you will write a function that takes in a string representing an expression and returns an integer representing its result. The input string will not contain any spaces. The following are examples of input and corresponding output:
Input:
3+5
Output:
8
Input:
3+5*7
Output:
38
Input:
3*(5*(7+2))
Output:
135
The functionality for reading and printing answers is written in the class Main; your task is to complete the eval() method which takes in a string representing an arithmetic expression as described above and outputs a single integer representing the result of this expression. (Hint: Parentheses are only used in the second half of the test cases.)
You may import stuff from java.util, but that's it. Examples would be Stack, ArrayList, etc.
//Starter code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// read input
String expression = sc.nextLine();
// print the evaluated result
System.out.println(eval(expression));
}
public static int eval(String expression) {
// TODO complete this function
throw new UnsupportedOperationException();
}
}
The code has been modified to satisfy the requirements. In addition to eval() function we need two more function one to check precedence and one to reduce repeating codes
Main.java
import java.util.*;
public class Main {
public int evaluate(String expression){
//Stack_Numbers
Stack
//Stack_operators
Stack
int a,b;
for(int i=0; i
if(Character.isDigit(c)){
int num = 0;
while (Character.isDigit(c)) {
num = num*10 + (c-'0');
i++;
if(i < expression.length())
c = expression.charAt(i);
else
break;
}
i--;
numbers.push(num);
}else if(c=='('){
operations.push(c);
}
else if(c==')') {
while(operations.peek()!='('){
int output = performOperation(numbers, operations);
numbers.push(output);
}
operations.pop();
}
else if(c=='+'||c=='-'||c=='/'||c=='*'||c=='^'){
while(!operations.isEmpty() &&
precedence(c)
numbers.push(output);
}
operations.push(c);
}
}
while(!operations.isEmpty()){
int output = performOperation(numbers, operations);
numbers.push(output);
}
return numbers.pop();
}
static int precedence(char c){
switch (c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public int performOperation(Stack
int a = numbers.pop();
int b = numbers.pop();
char operation = operations.pop();
switch (operation) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
if (a == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return b / a;
}
return 0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String infixExpression = sc.nextLine();
Main infix = new Main();
System.out.println(infix.evaluate(infixExpression));
}
}
Output: