Access Millions of academic & study documents

Calc.java

Content type
User Generated
Subject
Computer Science
Type
Homework
Showing Page:
1/4
Program Output
package calc;
//using stack to implement the conversion
import java.util.Stack;
public class Calc
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
//stack operation
Stack<Integer> vals = new Stack<>();
//stack for operation
Stack<Character> opers;
opers = new Stack<>();
for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')

Sign up to view the full document!

lock_open Sign Up
Showing Page:
2/4
{
StringBuilder sbuf = new StringBuilder();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
sbuf.append(tokens[i++]);
vals.push(Integer.parseInt(sbuf.toString()));
}
// Current token is an opening brace, push it to 'opers'
else if (tokens[i] == '(')
opers.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')')
{
while (opers.peek() != '(')
vals.push(applyOp(opers.pop(), vals.pop(), vals.pop()));
opers.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
while (!opers.empty() && haspr(tokens[i], opers.peek()))
vals.push(applyOp(opers.pop(), vals.pop(), vals.pop()));
// Push current token to 'opers'.

Sign up to view the full document!

lock_open Sign Up
Showing Page:
3/4

Sign up to view the full document!

lock_open Sign Up
End of Preview - Want to read all 4 pages?
Access Now
Unformatted Attachment Preview
Program Output package calc; //using stack to implement the conversion import java.util.Stack; public class Calc { public static int evaluate(String expression) { char[] tokens = expression.toCharArray(); //stack operation Stack vals = new Stack(); //stack for operation Stack opers; opers = new Stack(); for (int i = 0; i < tokens.length; i++) { // Current token is a whitespace, skip it if (tokens[i] == ' ') continue; // Current token is a number, push it to stack for numbers if (tokens[i] >= '0' && tokens[i] = '0' && tokens[i] ...
Purchase document to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.
Studypool
4.7
Indeed
4.5
Sitejabber
4.4