Postfix stack calculator - java

I've created a stack calculator for my Java class to solve equations such as
2 + ( 2 * ( 10 – 4 ) / ( ( 4 * 2 / ( 3 + 4) ) + 2 ) – 9 )
2 + { 2 * ( 10 – 4 ) / [ { 4 * 2 / ( 3 + 4) } + 2 ] – 9 }
We are suppose to implement { } [ ] into our code. I did it with just parentheses. It works 100% with just ( ). When I try to add { } [ ], it goes bananas.
This is what I have so far:
package stackscalc;
import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;
class Arithmetic {
int length;
Stack stk;
String exp, postfix;
Arithmetic(String s) {
stk = new Stack();
exp = s;
postfix = "";
length = exp.length();
}
boolean isBalance() {
boolean fail = false;
int index = 0;
try {
while (index < length) {
char ch = exp.charAt(index);
switch(ch) {
case ')':
stk.pop();
break;
case '(':
stk.push(new Character(ch));
break;
default:
break;
}
index++;
}
} catch (EmptyStackException e) {
fail = true;
}
return stk.empty() && !fail;
}
void postfixExpression() {
String token = "";
Scanner scan = new Scanner(exp);
stk.clear();
while(scan.hasNext()) {
token = scan.next();
char current = token.charAt(0);
if (isNumber(token)) {
postfix = postfix + token + " ";
} else if(isParentheses(current)) {
if (current == '(') {
stk.push(current);
} else {
Character ch = (Character) stk.peek();
char nextToken = ch.charValue();
while(nextToken != '(') {
postfix = postfix + stk.pop() + " ";
ch = (Character) stk.peek();
nextToken = ch.charValue();
}
stk.pop();
}
} else {
if (stk.empty()) {
stk.push(current);
} else {
Character ch = (Character) stk.peek();
char top = ch.charValue();
if (hasHigherPrecedence(top, current)) {
stk.push(current);
} else {
ch = (Character) stk.pop();
top = ch.charValue();
stk.push(current);
stk.push(top);
}
}
}
}
try {
Character ch = (Character) stk.peek();
char nextToken = ch.charValue();
while (isOperator(nextToken)) {
postfix = postfix + stk.pop() + " ";
ch = (Character) stk.peek();
nextToken = ch.charValue();
}
} catch (EmptyStackException e) {}
}
boolean isNumber(String s) {
try {
int Num = Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
void evaluateRPN() {
Scanner scan = new Scanner(postfix);
String token = "";
stk.clear();
while(scan.hasNext()) {
try {
token = scan.next();
if (isNumber(token)) {
stk.push(token);
} else {
char current = token.charAt(0);
double t1 = Double.parseDouble(stk.pop().toString());
double t2 = Double.parseDouble(stk.pop().toString());
double t3 = 0;
switch (current) {
case '+': {
t3 = t2 + t1;
stk.push(t3);
break;
}
case '-': {
t3 = t2 - t1;
stk.push(t3);
break;
}
case '*': {
t3 = t2 * t1;
stk.push(t3);
break;
}
case '/': {
t3 = t2 / t1;
stk.push(t3);
break;
}
default: {
System.out.println("Reverse Polish Notation was unable to be preformed.");
}
}
}
} catch (EmptyStackException e) {}
}
}
String getResult() {
return stk.toString();
}
int stackSize() {
return stk.size();
}
boolean isParentheses(char current) {
if ((current == '(') || (current == ')')) {
return true;
} else {
return false;
}
}
boolean isOperator(char ch) {
if ((ch == '-')) {
return true;
} else if ((ch == '+')) {
return true;
}
else if ((ch == '*')) {
return true;
}
else if((ch == '/')) {
return true;
} else {
}
return false;
}
boolean hasHigherPrecedence(char top, char current) {
boolean HigherPre = false;
switch (current) {
case '*':
HigherPre = true;
break;
case '/':
HigherPre = true;
break;
case '+':
if ((top == '*') || (top == '/') || (top == '-')) {
HigherPre = false;
} else {
HigherPre = true;
}
break;
case '-':
if ((top == '*') || (top == '/') || (top == '-')) {
HigherPre = false;
} else {
HigherPre = true;
}
break;
default:
System.out.println("Higher Precedence Unsuccessful was unable to be preformed.");
break;
}
return HigherPre;
}
String getPostfix() {
return postfix;
}
}

What I am assuming is that (), {}, and [] all have the same weight in terms of order of operations, and you just need to modify your code in order to allow for all three interchangeably.
If that is the case, I would just use the matcher class with a simple regex check to see if the current char that you are looking at is either a parenthesis, curly brace, or bracket.
//convert char to string
String temp += currentChar;
//this will check for (, [, and { (need escapes because of how regex works in java)
Pattern bracePattern = Pattern.compile("[\(\{\[]");
Matcher matcher = numPatt.matcher(temp);
if(matcher.find()){
//you know you have a grouping character
}
This code should allow you to find all the opening grouping characters (just substitute (,{, and [ for ),} and ] in the regex to find closing characters). This can be used in your isParenthesis() method.

You could use a method like this to streamline checking if a '(', '[', or '{' is matched or not.
static char getExpected(char val){
char expected=' ';
switch (val) {
case '(':
expected=')';
break;
case '[':
expected=']';
break;
case '{':
expected='}';
break;
}
return expected;
}

Related

Checking if parentheses match always saying that they match

I am writing a program where I should check if the opening parenthesis matches the closing one. If it doesn't match, I should display No. Otherwise, I should display yes.
This is the function I wrote, taking the input from the input buffer. However, I just keep on receiving yes for the second test case, instead of YES NO YES but the other two cases are correct.
static String[] braces(String[] values) {
Stack<Character> st = new Stack<Character>();
String[] answer = new String[values.length];
for(int i =0; i<values.length;i++){
char[] crt = values[i].toCharArray();
for(char c : crt){
switch(c){
case '{':
case '(':
case '[':
st.push(c);
break;
case '}':
if(st.isEmpty() || (st.peek() != '{'))
{
answer[i]= "NO";
break;
}
st.pop();
case ')':
if(st.isEmpty() || (st.peek() != '('))
{
answer[i]= "NO";
break;
}
st.pop();
case ']':
if(st.isEmpty() || (st.peek() != '['))
{
answer[i]= "NO";
break;
}
st.pop();
}
}
if(st.isEmpty() && answer[i].equals("NO") ){
answer[i]="YES";
System.out.println("I set answer[" + i + "] = YES due to stack being empty");
}
else
{
answer[i]="NO";
System.out.println("I set answer[" + i + "] = NO due to stack being non-empty");
}
st.clear();
}
return answer;
}
Change stack.firstElement() to stack.peek(), you need the stack top instead of the first element. (firstElement is not a Stack method)
The great secret of StackOverflow is that it's not actually full of gurus who look at your code the way Neo looks at The Matrix. It's just people examining how your programs runs.
You can do this yourself, and the most ancient and trivial way is through so-called "print debugging".
In short, you just add print statements that prints what your code is doing, and then you follow along and compare it to what you think it should be doing. Here's your code with such print statements added:
import java.util.*;
public class Test {
static String[] braces(String[] values) {
Stack<Character> st = new Stack<Character>();
String[] answer = new String[values.length];
for(int i =0; i<values.length;i++){
char[] crt = values[i].toCharArray();
boolean an = false;
for(char c : crt){
switch(c){
case '{':
case '(':
case '[':
st.push(c);
break;
case '}':
if(st.isEmpty() || (st.firstElement() != '{'))
{
answer[i]= "NO";
System.out.println("I set answer[" + i + "] = NO due to mismatched }");
}
st.pop();
break;
case ')':
if(st.isEmpty() || (st.firstElement() != '('))
{
answer[i]= "NO";
System.out.println("I set answer[" + i + "] = NO due to mismatched )");
}
st.pop();
break;
case ']':
if(st.isEmpty() || (st.firstElement() != '['))
{
answer[i]= "NO";
System.out.println("I set answer[" + i + "] = NO due to mismatched ]");
}
st.pop();
break;
}
}
if(st.isEmpty()){
answer[i]="yes";
System.out.println("I set answer[" + i + "] = YES due to stack being empty");
}
else
{
answer[i]="no";
System.out.println("I set answer[" + i + "] = NO due to stack being non-empty");
}
st.clear();
}
return answer;
}
public static void main(String[] args) {
String[] result = braces(new String[] { "(foo}" });
for(String s : result) System.out.println("The final result is " + s);
}
}
And here's the output, running on the string (foo}:
I set answer[0] = NO due to mismatched }
I set answer[0] = YES due to stack being empty
The final result is yes
Welp, it looks like you're overwriting your previous answer. You should make sure the final test doesn't override the loop's conclusion.
The trivial hack would be to check if answer[i] is null, but the better way would be to create a second helper method boolean braces(String) that is free to return true or false at any time, and then simply call that function in a loop in your braces(String[])
In any case, this would have been my implementation:
import java.util.Stack;
class Test {
static char flip(char c) {
switch(c) {
case '}': return '{';
case ')': return '(';
case ']': return '[';
default: throw new IllegalArgumentException("Invalid paren " + c);
}
}
static boolean matched(String value) {
Stack<Character> st = new Stack<Character>();
for (int i=0; i<value.length(); i++) {
char c = value.charAt(i);
switch(c) {
case '{':
case '(':
case '[':
st.push(c);
break;
case '}':
case ')':
case ']':
if (st.isEmpty() || st.peek() != flip(c)) {
return false;
}
st.pop();
break;
}
}
return st.isEmpty();
}
static String[] braces(String[] values) {
String[] result = new String[values.length];
for(int i=0; i<result.length; i++) {
result[i] = matched(values[i]) ? "yes" : "no";
}
return result;
}
public static void main(String[] args) {
String[] input = new String[] { "}", "{}", "{()}", "asdf", "", "{[", "{[[([])]]}", "((foo))" };
String[] actual = braces(input);
String[] expected = new String[] { "no", "yes", "yes", "yes", "yes", "no", "yes", "yes" };
for(int i=0; i<actual.length; i++) {
if(!actual[i].equals(expected[i])) {
System.out.println("Failed: " + input[i] + " should have been " + expected[i]);
System.exit(1);
}
}
System.out.println("OK");
}
}
import java.util.*;
import java.util.stream.Collectors;
public class Test {
static final Map<Character, Character> PARENS;
static final Set<Character> CLOSING_PARENS;
static {
PARENS = new HashMap<>();
PARENS.put('{', '}');
PARENS.put('[', ']');
PARENS.put('(', ')');
CLOSING_PARENS = new HashSet<>(PARENS.values());
}
public static void main(String[] args) {
print(braces("(foo}","[]","()","{}","[{}]","([{}])","[[]]"));
print(braces("[","]","][","[{]}"));
// test case 2 ...
print(braces("{[()]}","{[(])}","{{[[(())]]}}"));
// ... prints YES NO YES ...
}
static void print(String ... values){
for(String str : values){
System.out.print(str + " ");
}
System.out.println();
}
static String [] braces(String ... values) {
return Arrays.stream(values)
.map(Test::isBalanced)
.map(b -> b ? "YES" : "NO")
.collect(Collectors.toList()).toArray(new String[values.length]);
}
static boolean isBalanced(String token){
Stack<Character> stack = new Stack<>();
for(char c : token.toCharArray()){
if (PARENS.keySet().contains(c)){
stack.push(c);
} else if(CLOSING_PARENS.contains(c)){
if(stack.isEmpty() || !PARENS.get(stack.pop()).equals(c)) {
return false;
}
}
}
return stack.isEmpty();
}
}
you just have to make the following changes
Replace firstElement() with peek() in all cases
remove the following statement from the first two cases
stack.pop();
break;
check if stack is empity at the last case
if(!stack.isEmpty())
corrected code:
public class ParenMatch{
public static void main(String[] args){
String[] str = { "{}[](){[}]","{[()]}{[(])}{{[[(())]]}}","", "}][}}(}][))][](){()}()({}([][]))[](){)[](}]}]}))}(())(([[)"};
System.out.println(Arrays.toString(braces(str)));
}
public static String[] braces(String[] values)
{
Stack<Character> stack = new Stack<Character>();
String[] isCorrect = new String[values.length];
for (int i = 0; i < values.length; i++)
{
char[] crt = values[i].toCharArray();
boolean an = false;
for (char c : crt)
{
switch(c)
{
case '{':
case '(':
case '[':
stack.push(c);
break;
case '}':
if (stack.isEmpty() || (stack.peek() != '{'))
{
isCorrect[i] = "NO";
}
//stack.pop();
//break;
case ')':
if (stack.isEmpty() || (stack.peek() != '('))
{
isCorrect[i] = "NO";
}
//stack.pop();
//break;
case ']':
if (stack.isEmpty() || (stack.peek() != '['))
{
isCorrect[i] = "NO";
}
if(!stack.isEmpty())
stack.pop();
break;
}
}
if (stack.isEmpty())
{
isCorrect[i] = "yes";
}
else
{
isCorrect[i] = "no";
}
stack.clear();
}
return isCorrect;
}
}
input:
String[] str = { "{}[](){[}]","{[()]}{[(])}{{[[(())]]}}","", "}][}}(}][))][](){()}()({}([][]))[](){)[](}]}]}))}(())(([[)"};
output:
[yes, yes, yes, no]
static String[] braces(String[] values) {
Stack<Character> st = new Stack<Character>();
String []answer = new String[values.length];
Boolean isCorrect = false;
for(int i =0; i< values.length;i++)
{
isCorrect = true;
st.clear();
char crt[] = values[i].toCharArray();
for(char c : crt)
{
switch(c)
{
case'{':
case'[':
case'(':
st.push(c);
break;
case'}':
if(st.isEmpty() || st.peek() != '{')
{
System.out.println("Hellooo");
answer[i] ="NO";
isCorrect = false;
}
if(!st.isEmpty())
{
st.pop();
}
break;
case']':
if(st.isEmpty() || st.peek() != '[')
{
System.out.println("Hell");
answer[i] ="NO";
isCorrect = false;
}
if(!st.isEmpty())
{
st.pop();
}
break;
case')':
if(st.isEmpty() || st.peek() != '(')
{
isCorrect = false;
}
if(!st.isEmpty()) {
st.pop();
}
break;
}
}
if(isCorrect && st.isEmpty())
{
answer[i] = "YES";
System.out.println("Hello");
}else answer[i] = "NO";
}
return answer;
}

Conversion of an infix operation to a postfix operation

The code takes in an infix operation and converts it to a postfix operation. I have been able to to the conversion. The problem I'm facing is the spacing between operators. Also, I'd like to know how the postfix operation can be evaluated.
import java.io.IOException;
public class InToPost {
private Stack theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);
break;
case '*':
case '/':
case '%':
gotOper(ch, 2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
System.out.println(output);
return output;
}
public void gotOper(char opThis, int prec1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while (!theStack.isEmpty()) {
char chx = theStack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "13 + 23 - 42 * 2";
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
The postfix output for this is:
13 23 + 42 2*-
whereas I am trying to get an output that looks like this:
13 23 + 42 2 * -
I am unable to space the operator in the output.

Unknown error in converting a multiple digit infix expression to postfix

The function code for converting infix to postfix expression, as follows
package swapnil.calcii;
import android.util.Log;
import java.util.Stack;
public class Calculate {
private static final String operators = "-+/*";
private static final String operands = "0123456789";
public int evalInfix(String infix) {
return evaluatePostfix(convert2Postfix(infix));
}
public String convert2Postfix(String infixExpr) {
char[] chars = infixExpr.toCharArray();
Stack<String> stack = new Stack<String>();
StringBuilder out = new StringBuilder(infixExpr.length());
for (char c : chars) {
if (isOperator(c)) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
if (operatorGreaterOrEqual(stack.peek(), c)) {
out.append(stack.pop());
} else {
break;
}
}
String s = ""+c;
stack.push(s);
}
else if (c == '(') {
String s = ""+c;
stack.push(s);
} else if (c == ')') {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
out.append(stack.pop());
}
if (!stack.isEmpty()) {
stack.pop();
}
} else if (isOperand(c)) {
try{
StringBuilder num = new StringBuilder();
while(isOperand(stack.peek().charAt(0))) {
num.append(stack.pop());
out.append(num);
}
} catch (Exception e) {
Log.d("errrr", "error in inserting " + e.getMessage());
out.append(c);
}
out.append(c);
}
}
while (!stack.empty()) {
out.append(stack.pop());
}
return out.toString();
}
public int evaluatePostfix(String postfixExpr) {
char[] chars = postfixExpr.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
for (char c : chars) {
if (isOperand(c)) {
stack.push(c - '0'); // convert char to int val
} else if (isOperator(c)) {
int op1 = stack.pop();
int op2 = stack.pop();
int result;
switch (c) {
case '*':
result = op1 * op2;
stack.push(result);
break;
case '/':
result = op2 / op1;
stack.push(result);
break;
case '+':
result = op1 + op2;
stack.push(result);
break;
case '-':
result = op2 - op1;
stack.push(result);
break;
}
}
}
return stack.pop();
}
private int getPrecedence(char operator) {
int ret = 0;
if (operator == '-' || operator == '+') {
ret = 1;
} else if (operator == '*' || operator == '/') {
ret = 2;
}
return ret;
}
private boolean operatorGreaterOrEqual(String op1, char op2) {
char op = op1.charAt(0);
return getPrecedence(op) >= getPrecedence(op2);
}
private boolean isOperator(char val) {
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val) {
return operands.indexOf(val) >= 0;
}
}
crashes with unknown error.
I've written it myself and I can't figure out where I am going wrong.
Function works fine, if pushing one char when checking isOperand(c)
But using StringBuilder to push a multiple digit number crashes the code.
Help

Get the Java program to read parenthesis, brackets, and curly braces

I am writing a program that verifies arithmetic expression are correctly formed. (For example: Correct form "2 + (2-1)", incorrect form ")2+(2-1")
Once it's been verified, the program will compute the results.
At the moment, it can compute anything in parenthesis easily. But if there was a bracket involved (For example, "2 [ 3 + (1) ]") The program verifies the expression is correct, but cannot calculate the results.
Here is the code I'm concerned about
void postfixExpression() {
stk.clear(); // Re-using the stack object
Scanner scan = new Scanner(expression);
char current;
// The algorithm for doing the conversion.... Follow the bullets
while (scan.hasNext()) {
String token = scan.next();
if (isNumber(token))
{
postfix = postfix + token + " ";
} else {
current = token.charAt(0);
if (isParentheses(current))
{
if (stk.empty() || current == Constants.LEFT_NORMAL) {
// push this element on the stack;
stk.push(new Character(current));
} else if (current == Constants.RIGHT_NORMAL) {
try {
Character ch = (Character) stk.pop();
char top = ch.charValue();
while (top != Constants.LEFT_NORMAL) {
postfix = postfix + top + " ";
ch = (Character) stk.pop();
top = ch.charValue();
}
} catch (EmptyStackException e) {
}
}
} else if (isOperator(current))//
{
if (stk.empty()) {
stk.push(new Character(current));
} else {
try {
char top = (Character) stk.peek();
boolean higher = hasHigherPrecedence(top, current);
while (top != Constants.LEFT_NORMAL && higher) {
postfix = postfix + stk.pop() + " ";
top = (Character) stk.peek();
}
stk.push(new Character(current));
} catch (EmptyStackException e) {
stk.push(new Character(current));
}
}
}// Bullet # 3 ends
}
} // Outer loop ends
try {
while (!stk.empty()) // Bullet # 4
{
postfix = postfix + stk.pop() + " ";
}
} catch (EmptyStackException e) {
}
}
I've created two methods: isBracket, and isCurly. At first, I thought the most appropriate solution is to just include the two method in the same manner as isParentheses. Like so:
if (isParentheses(current))
{
if (stk.empty() || current == Constants.LEFT_NORMAL) {
// push this element on the stack;
stk.push(new Character(current));
} else if (current == Constants.RIGHT_NORMAL) {
try {
Character ch = (Character) stk.pop();
char top = ch.charValue();
while (top != Constants.LEFT_NORMAL) {
postfix = postfix + top + " ";
ch = (Character) stk.pop();
top = ch.charValue();
}
} catch (EmptyStackException e) {
}
}
if (isCurly(current))
{
if (stk.empty() || current == Constants.LEFT_CURLY) {
// push this element on the stack;
stk.push(new Character(current));
} else if (current == Constants.RIGHT_CURLY) {
try {
Character ch = (Character) stk.pop();
char top = ch.charValue();
while (top != Constants.LEFT_CURLY) {
postfix = postfix + top + " ";
ch = (Character) stk.pop();
top = ch.charValue();
}
} catch (EmptyStackException e) {
if (isBracket(current))
{
if (stk.empty() || current == Constants.LEFT_SQUARE) {
// push this element on the stack;
stk.push(new Character(current));
} else if (current == Constants.RIGHT_SQUARE) {
try {
Character ch = (Character) stk.pop();
char top = ch.charValue();
while (top != Constants.LEFT_SQUACRE) {
postfix = postfix + top + " ";
ch = (Character) stk.pop();
top = ch.charValue();
}
} catch (EmptyStackException e) {
But the program still would not consider the brackets and the braces (but it's still reading the parentheses fine.)
I'm not using the methods correctly from what I understand, but how can I use them appropriately?
Here's an idea I thought of for taking a different approach to this problem.
You could split up the numbers and brackets into two different stacks, making it easier to ensure the expression is formed correctly.
At the beginning of the code, you could declare two stack variables:
Stack<Integer> numbers = new Stack<Integer>();
Stack<Character> operators = new Stack<Character>();
And then push operators and numbers accordingly.
This a very quick method I created that would demonstrate this implementation of using two Stack objects:
public double doCalculation(String input) throws DataFormatException {
if (input == null) {
return 0;
}
char[] characters = input.toCharArray();
for (char character: characters) {
try {
// tries to push the number onto the number stack
numbers.push(Integer.parseInt("" + character));
} catch (NumberFormatException e1) {
// if this is caught, this means the character is non-numerical
operators.push(character);
}
}
while (operators.size() > 0) {
int i = numbers.pop();
int j = numbers.pop();
char operator = operators.pop();
switch (operator) {
case '+':
numbers.push(j + i);
break;
case '-':
numbers.push(j - i);
break;
case '*':
numbers.push(j * i);
break;
case '/':
numbers.push(j / i);
break;
case '^':
numbers.push((int)(Math.pow(j, i)));
break;
default:
throw new DataFormatException();
}
}
return numbers.pop();
}
Just for fun:
If this code is added to the catch block before the non-numerical character is pushed to the stack, it will calculate the equation in terms of order of operations:
char top;
try {
top = operators.peek();
} catch (EmptyStackException e2) {
operators.push(character);
continue;
}
if (getValue(character) > getValue(top)) {
operators.push(character);
continue;
} else {
try {
while (!(getValue(character) > getValue(operators.peek()))) {
char operator;
operator = operators.pop();
int i = numbers.pop();
int j = numbers.pop();
switch (operator) {
case '+':
numbers.push(j + i);
break;
case '-':
numbers.push(j - i);
break;
case '*':
numbers.push(j * i);
break;
case '/':
numbers.push(j / i);
break;
case '^':
numbers.push((int)(Math.pow(j, i)));
break;
default:
throw new DataFormatException();
}
}
} catch (EmptyStackException e3) {
operators.push(character);
continue;
}
Assuming a getValue() method is defined accordingly:
public int getValue(char character)
throws DataFormatException {
switch (character) {
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
default:
throw new DataFormatException();
}
}

Recognizing negative values when converting infix to postfix

This is my class:
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.List;
import java.util.Stack;
/**
*
* #author rtibbetts268
*/
public class InfixToPostfix
{
/**
* Operators in reverse order of precedence.
*/
private static final String operators = "_-+/*";
private static final String operands = "0123456789x";
public String xToValue(String postfixExpr, String x)
{
char[] chars = postfixExpr.toCharArray();
StringBuilder newPostfixExpr = new StringBuilder();
for (char c : chars)
{
if (c == 'x')
{
newPostfixExpr.append(x);
}
else
{
newPostfixExpr.append(c);
}
}
return newPostfixExpr.toString();
}
public String convert2Postfix(String infixExpr)
{
char[] chars = infixExpr.toCharArray();
StringBuilder in = new StringBuilder(infixExpr.length());
for (int i : chars)
{
if (infixExpr.charAt(i) == '-')
{
if (isOperand(infixExpr.charAt(i+1)))
{
if (i != infixExpr.length())
{
if (isOperator(infixExpr.charAt(i-1)))
in.append('_');
}
else
{
in.append(infixExpr.charAt(i));
}
}
else
{
in.append(infixExpr.charAt(i));
}
}
else
{
in.append(infixExpr.charAt(i));
}
}
chars = in.toString().toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder(in.toString().length());
for (char c : chars)
{
if (isOperator(c))
{
while (!stack.isEmpty() && stack.peek() != '(')
{
if (operatorGreaterOrEqual(stack.peek(), c))
{
out.append(stack.pop());
}
else
{
break;
}
}
stack.push(c);
}
else if (c == '(')
{
stack.push(c);
}
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
out.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else if (isOperand(c))
{
out.append(c);
}
}
while (!stack.empty())
{
out.append(stack.pop());
}
return out.toString();
}
public int evaluatePostfix(String postfixExpr)
{
char[] chars = postfixExpr.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
for (char c : chars)
{
if (isOperand(c))
{
stack.push(c - '0'); // convert char to int val
}
else if (isOperator(c))
{
int op1 = stack.pop();
int op2 = stack.pop();
int result;
switch (c) {
case '*':
result = op1 * op2;
stack.push(result);
break;
case '/':
result = op2 / op1;
stack.push(result);
break;
case '+':
result = op1 + op2;
stack.push(result);
break;
case '-':
result = op2 - op1;
stack.push(result);
break;
}
}
}
return stack.pop();
}
private int getPrecedence(char operator)
{
int ret = 0;
if (operator == '_')
{
ret = 0;
}
if (operator == '-' || operator == '+')
{
ret = 1;
}
else if (operator == '*' || operator == '/')
{
ret = 2;
}
return ret;
}
private boolean operatorGreaterOrEqual(char op1, char op2)
{
return getPrecedence(op1) >= getPrecedence(op2);
}
private boolean isOperator(char val)
{
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val)
{
return operands.indexOf(val) >= 0;
}
}
In it I change infix expressions to postfix expressions with the method convert2Postfix()
There is a small section in it at the very beginning where I am rewriting the string input with all negative numbers having a '_' infront of them instead of a "-". It doesn't work.
ex: change -4 to _4
What do I need to do to make this work?
You have a number of errors here, here is the first one:
for (int i : chars)
chars is converted to the corresponding int. For example if chars contains one single character 'A':
char [] chars = new char[1];
chars[0] = 'A';
for(int i: chars){
System.out.println(i); //You will have a '65' here
}
What you really mean is probably:
for (int i=0;i<chars.length;++i)
This is also wrong:
if (isOperator(infixExpr.charAt(i-1)))
It should be :
if (isOperator(infixExpr.charAt(i)))
Then there is a problem in the way you put and remove elements in the stack.
After all this changes you should also do this:
return out.reverse().toString();
instead of :
return out.toString();
Here is what I ended up with: http://pastebin.com/2TLqPUsH
(Change the name of the classes of course)

Categories