Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Calculator java program I need help in this method to read negative values such as ( 1 - 4 ) + ( 3 + -9

Calculator java program

I need help in this method to read negative values such as

( 1 - 4 ) + ( 3 + -9 ) * 5 = -6.0

public static double evalInfix(String s) { valStack = new Stack(); opStack = new Stack(); char[] tokens = s.toCharArray(); 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') { StringBuffer sbuf = new StringBuffer(); // There may be more than one digits in number while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') sbuf.append(tokens[i++]); valStack.push(Double.parseDouble(sbuf.toString())); } // Current token is an opening brace, push it to 'opStack' else if (tokens[i] == '(') opStack.push(tokens[i]); // Closing brace encountered, solve entire brace else if (tokens[i] == ')') { while (opStack.peek() != '(') valStack.push(doOp(opStack.pop(), valStack.pop(), valStack.pop())); opStack.pop(); } // Current token is an operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/' ||tokens[i] == '^') { // While top of 'opStack' has same or greater precedence to current // token, which is an operator. Apply operator on top of 'opStack' // to top two elements in valStack stack while (!opStack.empty() && prec(tokens[i]) <= prec(opStack.peek())) valStack.push(doOp(opStack.pop(), valStack.pop(), valStack.pop())); // Push current token to 'opStack'. opStack.push(tokens[i]); } } // Entire expression has been parsed at this point, apply remaining // ops to remaining values while (!opStack.empty()) valStack.push(doOp(opStack.pop(), valStack.pop(), valStack.pop())); // Top of 'values' contains result, return it return valStack.pop(); }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

PostgreSQL Up And Running A Practical Guide To The Advanced Open Source Database

Authors: Regina Obe, Leo Hsu

3rd Edition

1491963417, 978-1491963418

More Books

Students also viewed these Databases questions

Question

Conduct a needs assessment. page 269

Answered: 1 week ago