Question

In: Computer Science

SOLUTION IN JAVAIn this problem, we will be evaluating simple math expressionsthat contain numbers,...

SOLUTION IN JAVA

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.

Solutions

Expert Solution

/* I have already given this answer before and it's working with n digit also */

import java.util.Scanner;
import java.util.Stack;

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) {
//Stack for Numbers
Stack numbers = new Stack<>();

//Stack for operators
Stack operations = new Stack<>();
for(int i=0; i char c = expression.charAt(i);
//check if it is number
if(Character.isDigit(c)){
//Entry is Digit, it could be greater than one digit number
int num = 0;
while (Character.isDigit(c)) {
num = num*10 + (c-'0');
i++;
if(i < expression.length())
c = expression.charAt(i);
else
break;
}
i--;
//push it into stack
numbers.push(num);
}else if(c=='('){
//push it to operators stack
operations.push(c);
}
//Closed brace, evaluate the entire brace
else if(c==')') {
while(operations.peek()!='('){
int output = performOperation(numbers, operations);
//push it back to stack
numbers.push(output);
}
operations.pop();
}
// current character is operator
else if(isOperator(c)){
//1. If current operator has higher precedence than operator on top of the stack,
//the current operator can be placed in stack
// 2. else keep popping operator from stack and perform the operation in numbers stack till
//either stack is not empty or current operator has higher precedence
//than operator on top of the stack
while(!operations.isEmpty() && precedence(c) int output = performOperation(numbers, operations);
//push it back to stack
numbers.push(output);
}
//now push the current operator to stack
operations.push(c);
}
}
//If here means entire expression has been processed,
//Perform the remaining operations in stack to the numbers stack

while(!operations.isEmpty()){
int output = performOperation(numbers, operations);
//push it back to stack
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 static int performOperation(Stack numbers, Stack operations) {
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 boolean isOperator(char c){
return (c=='+'||c=='-'||c=='/'||c=='*'||c=='^');
}
}

/* OUTPUT */


Related Solutions

In this problem, we will be evaluating simple math expressionsthat contain numbers, +, *, (,...
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+5Output:8Input:3+5*7Output:38Input:3*(5*(7+2))Output:135The functionality for reading and printing answers is written in the class Main; your task is to complete the eval() method which takes in a...
Problem in chapter 15 of Java book. Need a solution please! Problem: Standard telephone keypads contain...
Problem in chapter 15 of Java book. Need a solution please! Problem: Standard telephone keypads contain the digits zero through nine. The numbers two through nine each have three letters associated with them (as seen below). Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use this tool to develop the...
Mixing Math problem
Sterling Silver is 92.5% pure silver. How many grams of Sterling Silver must be mixed to a 90% Silver alloy to obtain a 500g of a 91% Silver alloy?
In a lab, we are required to make a 100ml solution that contain: 54.30mg/L sodium salicylate,...
In a lab, we are required to make a 100ml solution that contain: 54.30mg/L sodium salicylate, 0.020M FeCl3, 0.050 M HCl. I will also need to create a blank solution that contains 0.020 M FeCl3 and 0.050 M HCI. The blank solution is also 100.00 mL. At the end, we are required to get an absorbance at 520 nm. What should I do to prepare the solutions? Please give detailed instructions. Thank you very much!
In this problem we consider another way to think about the rational numbers. Normally we would...
In this problem we consider another way to think about the rational numbers. Normally we would write fractions as p/q for p ∈ Z and q ∈ N. In this problem we represent fractions as ordered pairs. So let S = {(p, q)|p ∈ Z and q ∈ N}. For ordered pairs (p, q) and (r, s) in S define (p, q)R(r, s) if and only if ps = qr. You should think about how this is related to the...
[Discrete math] Show that it is possible to arrange the numbers 1, 2, . . ....
[Discrete math] Show that it is possible to arrange the numbers 1, 2, . . . , n in a row so that the average of any two of these numbers never appears between them. [Hint: Show that it suffices to prove this fact when n is a power of 2. Then use mathematical induction to prove the result when n is a power of 2.] I saw the solution but I don't understand why permutation pi is using here.....
We are interested in whether math score (math – a continuous variable) is a significant predictor...
We are interested in whether math score (math – a continuous variable) is a significant predictor of science score (science – a continuous variable) using the High School and Beyond (hsb2) data. State the null and alternative hypotheses and the level of significance you intend to use. Ho:β=0 H1:β≠0 Alph:0.05 Write the equation for the appropriate test statistic. t =b/SE(b) What is your decision rule? Be sure to include the degrees of freedom. If our t value is greater than...
Java basic sorting problem Supposed I have a simple array list storing the telephone numbers. How...
Java basic sorting problem Supposed I have a simple array list storing the telephone numbers. How can I sort the numbers in descending order with different ways? Give ArrayList<String> tel = ["11223344", "55442211", "99881122", "99002211", "34446666", "12342353"] I come up a solution using Collections.sort(tel), but it requires a compare method and I have no idea its contents and also the position of the method. Would you suggest 2 or 3 ways and write the code to achieve my purpose?
In math class, a student has written down a sequence of 16 numbers on the blackboard....
In math class, a student has written down a sequence of 16 numbers on the blackboard. Below each number, a second student writes down how many times that number occurs in the se‐ quence. This results in a second sequence of 16 numbers. Below each number of the second se‐ quence, a third student writes down how many times that number occurs in the second se‐ quence. This results in a third sequence of numbers. In the same way, a...
In math class, a student has written down a sequence of 16 numbers on the blackboard....
In math class, a student has written down a sequence of 16 numbers on the blackboard. Below each number, a second student writes down how many times that number occurs in the sequence.  This results in the second sequence of 16 numbers. Below each number of the second sequence, a third student writes down how many times that number occurs in the second sequence. This results in the third sequence of numbers. In the same way, a fourth, fifth, sixth, and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT