Question

In: Computer Science

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+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();
}
}

Solutions

Expert Solution

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 numbers = new Stack<>();

//Stack_operators
Stack operations = new Stack<>();
int a,b;
for(int i=0; i char c = expression.charAt(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) int output = performOperation(numbers, operations);
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 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 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:


Related Solutions

SOLUTION IN JAVAIn this problem, we will be evaluating simple math expressionsthat contain numbers,...
SOLUTION IN JAVAIn 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...
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 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...
Scarlett is practicing math fluency. She has 100 math operation flashcards with 42 addition problem cards,...
Scarlett is practicing math fluency. She has 100 math operation flashcards with 42 addition problem cards, 56 subtraction cards, and 2 multiplication cards. Scarlett will time herself to see how fast she can solve the problems on seven cards. She chooses her seven cards and they are all addition cards. Is choosing all addition cards likely? Explain by running a simulation. (10 points) Part A: State the problem or question and assumptions. (2 points) Part B: Describe the process for...
Problem 9-1 Sensitivity Analysis and Break-Even Point We are evaluating a project that costs $520,000, has...
Problem 9-1 Sensitivity Analysis and Break-Even Point We are evaluating a project that costs $520,000, has a five-year life, and has no salvage value. Assume that depreciation is straight-line to zero over the life of the project. Sales are projected at 64,000 units per year. Price per unit is $46, variable cost per unit is $26, and fixed costs are $832,000 per year. The tax rate is 35 percent, and we require a return of 20 percent on this project....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT