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.....
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...
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...
This is math probability questions. Please write the solution & answer on the paper and upload...
This is math probability questions. Please write the solution & answer on the paper and upload a picture of it if possible. (Don'y use R plz) 1. One fair coin and two unfair coins where heads is 5 times as likely as tails are put into a bag. One coin is drawn at random and then flipped twice. If at least one of the flips was tails, what is the probability an unfair coin was flipped? 2. There are 4...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT