Infix to Postfix Notation Parentheses issue - java

So I am currently working on a project to convert infix to postfix notation and I am almost finished with the project. It correctly converts infix to postfix until I try adding parentheses it ends up incorrectly formatted.
static int precedence(String c){
switch(c){
case"+":
case"-":
return 1;
case"*":
case"/":
return 2;
default:
return -1;
}
}
I believe that this next part the code is good because everything works correctly without parentheses.
// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException
{
String[] tokens = infix.split("");
String result= " ";
Stack<String> stack= new Stack<>();
for(int i = 0; i<tokens.length; i++){
String current = tokens[i];
if(precedence(current)>0){
while(!stack.isEmpty() && precedence(stack.peek())>= precedence(current)){
result += stack.pop() + " ";
}
stack.push(current);
} else if(!stack.isEmpty()&& precedence(stack.peek())<= precedence(current)){
result += stack.pop() + " ";
}
I believe that the issue I'm having is with the next part of my code involving manipulating the parentheses.
else if(current== ")"){
String s = stack.pop();
while(s !="("){
result += s;
s= stack.pop();
}
} else if(current == "("){
stack.push(current);
}
else {
result += current + " ";
}
}
for(int i=0;i <= stack.size(); i++){
result+= stack.pop() + " ";
}
return result;
}
This is my main method and I have included an example output.
import java.util.Stack;
public class RPNcalc {
public static void main( String[] args) throws InvalidInfixEquationException, InvalidPostfixEquationException {
String result= "(3+4)/3*2"; // output 3 4 + 3 / 2 *
System.out.println(ConvertToPostfix(result));
This is the output that I am getting
( 3 4 ) 3 / 2 * +

Related

Decode String in Java

I am trying to convert this Python Solution in Java. For some reason, my Java Solution is not working. How can this be done correctly?
https://leetcode.com/problems/decode-string/description/
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Python Solution:
class Solution:
def decodeString(self, s: str) -> str:
stack = []
for char in s:
if char is not "]":
stack.append(char)
else:
sub_str = ""
while stack[-1] is not "[":
sub_str = stack.pop() + sub_str
stack.pop()
multiplier = ""
while stack and stack[-1].isdigit():
multiplier = stack.pop() + multiplier
stack.append(int(multiplier) * sub_str)
return "".join(stack)
Java Attempt:
class Solution {
public String decodeString(String s) {
Deque<String> list = new ArrayDeque<String>();
String subword = "";
String number = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ']' ) {
list.add(String.valueOf(s.charAt(i)));
}
else {
subword = "";
while (list.size() > 0 && !list.getLast().equals("[") ) {
subword = list.pop() + subword;
}
if (list.size() > 0) list.pop();
number = "";
while (list.size() > 0 && isNumeric(list.getLast())){
number = list.pop() + number;
}
for (int j = 1; (isNumeric(number) && j <= Integer.parseInt(number)); j++) list.add(subword);
}
}
return String.join("", list);
}
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
}
The reason why your posted code is not working is because the pop() method in python removes the last element by default.
But in Java, the ArrayDeque class's pop() method removes the first element.
In order to emulate the python code with the ArrayDeque, you'll need to use the removeLast() method of the ArrayDeque instance instead.
public class Solution{
public static String decodeString(String s) {
StringBuilder stack = new StringBuilder();
for(char c : s.toCharArray()) {
if(c != ']') {
stack.append(c);
} else {
StringBuilder sub_str = new StringBuilder();
while(stack.charAt(stack.length() - 1) != '[') {
sub_str.insert(0, stack.charAt(stack.length() - 1));
stack.deleteCharAt(stack.length() - 1);
}
stack.deleteCharAt(stack.length() - 1);
StringBuilder multiplier = new StringBuilder();
while(stack.length() > 0 && Character.isDigit(stack.charAt(stack.length() - 1))) {
multiplier.insert(0, stack.charAt(stack.length() - 1));
stack.deleteCharAt(stack.length() - 1);
}
for(int i = 0; i < Integer.parseInt(multiplier.toString()); i++) {
stack.append(sub_str);
}
}
}
return stack.toString();
}
public static void main(String[] args) {
System.out.println( decodeString("3[a2[c]]"));
//Output: "accaccacc"
System.out.println( decodeString("3[a]2[bc]"));
//Output: "aaabcbc"
}
}

Converting infix to postfix and getting an EmptyStackException

I am working on a project to convert infix notation to postfix notation and then evaluate the equation. I established the precedence for each operator. When I use the ConvertToPostfix method I get the Exception. I understand the concept of the reverse polish notation calculator and I am just struggling with doing it with my code. I am new to stack overflow so if there is something that may seem a little confusing just let me know and ill try to edit it.
import java.util.Stack;
public class RPNCalctest {
public static void main( String[] args) throws InvalidInfixEquationException {
String example= "3+4/3*2"; //postfix notation would be 3 4 3 / 2 * +
System.out.println(ConvertToPostfix(example));
// TODO
}
//establish precedence
static int precedence(String c){
switch(c){
case"+":
case"-":
return 1;
case"*":
case"/":
return 2;
case")":
return 3;
case"(":
return 4;
default:
return -1;
}
}
// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException {
String[] tokens = infix.split(" ");
String result = "";
Stack<String> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String current = tokens[i];
if (precedence(current) > 0) {
while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(current)) {
result += stack.pop() + " ";
}
stack.push(current);
} else {
result += current + " ";
}
}
for (int i = 0; i <= stack.size(); i++) {
result += stack.pop();
}
return result;
}
}
Exception in thread "main" java.util.EmptyStackException
at java.base/java.util.Stack.peek(Stack.java:101)
at java.base/java.util.Stack.pop(Stack.java:83)
at RPNCalctest.ConvertToPostfix(RPNCalctest.java:50)
at RPNCalctest.main(RPNCalctest.java:7)
Your problem is here. You pop off one more entry than there is.
for (int i = 0; i <= stack.size(); i++) {
result += stack.pop();
}
Consider size=2. You execute the loop for i=0, 1, 2.
I assume that the 'pop' line is line 53 as indicated in the stack trace, so for future reference, that's useful debugging info and you should use it.
It might be clearer if that loop were coded:
while (!stack.isEmpty()) {
result += stack.pop();
}
No need for the extraneous variable 'i'.

I'm trying to change infix to postfix in java, what is the problem?

I want to convert infix to postfix with stack data structure.
In this code, I didn't consider the case of * and /.
example input: 10 - ( 3 + 4 ) - 1
correct output is: 10 3 4 + - 1 -
but my output is: 10 3 4 + 1 - -
And this is part of my code. I checked some part that I thought that is wrong.
operator is name of stack I made.
public String infix to (String infix) throws ArrayIndexOutOfBoundsException {
int result=0;
arr = infix.split(" ");
String element = "";
String postfix="";
for(int i=0; i<arr.length; i++) {
element = arr[i];
if(element.equals("+")||element.equals("-")) {
operator.push(element);
}
else if(element.equals("(")) {
operator.push(element);
}
else if(element.equals(")")) {
//**As I think, this part might wrong**
while((!operator.empty())||(!operator.peek().equals("("))){
postfix = postfix.concat(operator.pop());
postfix = postfix.concat(" ");
if(operator.peek().equals("(")) {
operator.pop();
}
break;
}
}
else if(isNum(element)){
postfix = postfix.concat(element);
postfix = postfix.concat(" ");
}
}
while(!operator.empty()) {
postfix = postfix.concat(operator.pop());
postfix = postfix.concat(" ");
}
return postfix;
}
public static boolean isNum(String s) {
try {
Integer.parseInt(s);
return true;
}
catch(NumberFormatException e) {
return false;
}
}
thank you all.
Change this (!operator.empty())||(!operator.peek().equals("(")) to (!operator.empty()) && (!operator.peek().equals("("))
while((!operator.empty()) && (!operator.peek().equals("("))){
postfix = postfix.concat(operator.pop());
postfix = postfix.concat(" ");
if( (!operator.empty()) && (!operator.peek().equals("("))) {
break; //invalid
else
operator.pop();
}
}

Stack problem java. Postfix Evaluation

Hey Guys I'm having a problem when I run my program. In the PostfixEvaluate() Method is where it takes in a string and solves the postfix problem and returns it. Well when I go to run it, I'm getting a bunch of random numbers(some repeated), I'm going crazy because I don't know what else to try and I've spent more time on this than it should normally take.
Heres the PostfixEvaluate Method:
public int PostfixEvaluate(String e){
//String Operator = "";
int number1;
int number2;
int result=0;
char c;
//number1 = 0;
//number2 = 0;
for(int j = 0; j < e.length(); j++){
c = e.charAt(j);
if (c != '+'&& c!= '*' && c!= '-' && c!= '/') {
//if (c == Integer.parseInt(e)) {
s.push(c);
}
else {
number1 = s.pop();
number2 = s.pop();
switch(c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
} s.push(result);
}
System.out.println(result);
}
return s.pop();
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
String y = new String("(z * j)/(b * 8) ^2");
String x = new String("2 3 + 9 *");
TestingClass clas = new TestingClass(st);
clas.test(y);
clas.PostfixEvaluate(x);
}
}
This is the Stack Class:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(int result) {
top++;
stack[top] = (char)result;
}
public int pop() {
int x;
x = stack[top];
//top = top - 1;
top--;
return x;
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty " + "Equation Good");
return true;
}
else
System.out.println("Equation is No good");
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
}
It looks to me like you aren't handling spaces at all.
This means that when you put in a space, it is implicitly converting the character space to the ascii value of it (32) when it pops it off the stack during an operation. Also, it looks like you are assuming that all numbers/results will be single digit, and casting from char to int, which is not what you want to do, since that will convert the char to the ascii value of the char, ' ' -> 32, '3' -> 51, etc.
If I were you, I would do this for your loop in PostfixEvaluate:
while(!e.equals("")){
string c;
int space = e.indexOf(' ');
if(space!=-1){
c = e.substring(0,space);
e = e.substring(space+2);
} else{
c = e;
e = "";
}
if (!c.equals("+")&& !c.equal("*") && !c.equals("-") && !c.equals("/")) {
//...
}
and change your stack to hold strings or ints.
The problem is that you are pushing char onto a stack as an int, so you are unintentionally working with the ascii representations of numbers, which is not the actual value of the number.
Instead of this complicated character walking, tokenize the input string using String.split(). Example:
String[] tokens = e.split(" ");
for(String token:tokens){
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
....
}
}
You need to split the string into tokens first:
/* Splits the expression up into several Strings,
* all of which are either a number or and operator,
* none of which have spaces in them. */
String [] expressionAsTokens = e.split(" ");
Then you need to make sure you compare Strings, not chars:
//compare strings instead of chars
String token = expressionAsTokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
//same code as you had before
}
Also, is there any reason you are storing everything as a char array in your Stacked class? Your pop() method returns and integer, yet everything is stored as a char.
For this application, everything should be stored as an integer:
public class Stacked {
int stack[]; // array is of type integer
int top;
int maxLen;
// constructor
public void push() {/*...*/}
public int pop() {/*...*/} //pop returns an int as before
//...
}
One final note: Be careful what order you add and subtract the numbers in. I don't remember if postfix operands are evaluated left first or right first, but make sure you get them in the right order. As you have it now, 2 3 - 4 * would evaluate as 4 * (3 - 2) and I think it should be (2 - 3) * 4. This won't matter with adding and multiplying, but it will with subtracting and dividing.

Getting wrong outputs in infix to postfix application with java

i recently wrote a java program that takes an infix expression and converts it into a postfix expression. It works for the most part but i am getting wrong outputs for some expressions. For example the expression a+b+c+d+e will output abcde+++++ when it should output
a b + c + d + e +.
import java.util.Stack;
public class ITP {
public static Stack<Character> stack;
public static String inFixExp;
public static String postFixExp = "";
public static String infixToPostfix(String exp){
ITP o = new ITP();
stack = new Stack<Character>();
inFixExp = exp;
for (int i = 0; i < inFixExp.length(); i++) {
if (inFixExp.charAt(i) == '(')
stack.push(inFixExp.charAt(i));
else if (inFixExp.charAt(i)==')'){
while (stack.peek()!='('){
postFixExp += stack.pop();
}
stack.pop();
}else if ((inFixExp.charAt(i)=='*')||(inFixExp.charAt(i)=='/')||(inFixExp.charAt(i)=='+')||(inFixExp.charAt(i)=='-')){
while(!stack.isEmpty() && o.getPredence(inFixExp.charAt(i)) < o.getPredence(stack.peek()))
postFixExp += stack.pop();
stack.push(inFixExp.charAt(i));
}else
postFixExp += inFixExp.charAt(i);
}
while(!stack.isEmpty())
postFixExp += stack.pop();
return postFixExp;
}
public int getPredence(Object op) {
if((op.equals("*")) || (op.equals("/")))
return 3;
else if((op.equals("+"))||(op.equals("-")))
return 1;
else
return 0;
}
}
I found out that if i change the < with <= in line 24 it will fix this problem but then i will get an empty stack error and some other expressions will output incorrectly, such as a+b*c which will output ab+c*, when it is supposed to be abc*+.
Your
if ((inFixExp.charAt(i) == '*') || ...
checks charAt() but your getPredence(precedence?) checks for a String, try comparing against a char instead.

Categories