Hello. I'm trying to write a program that will convert a user input infix expression into its postfix form. My current code is allowing the user to input a string, but it does nothing with the string. I'm fairly new to JAVA, thus I think I'm making a simple mistake in the main method. I'm using a generic class for a stacks implemented using arrays to store any data type. Thanks in advance for any help.

import java.io.*;
import java.util.*;
//begin coding for the stack interface
interface Stack<E>
{
    public boolean isEmpty();//tests is current stack is empty. Returns true if so, and false if not.
    public E top() throws StackException;//retrieves value at the top of the stack. Stack cannot be empty.
    public void push(E value) throws StackException;//pushes a value on the top of the stack. 
    public void pop() throws StackException;//removes a value from the top of the stack. Stack cannot be empty.
}//terminates coding of Stack interface

//begin coding for the objArrayStack class
class objArrayStack<E> implements Stack<E>
{
    //constructor
    public objArrayStack()
    {
        topValue=-1;
    }//terminates constructor
    public void push(E value)throws StackException
    {
        if(topValue<ArraySize-1)//currrent stack is not full
            {
                ++topValue;
                Info[topValue]=value;
            }//terminates if
        else //current stack is full
            throw new StackException("Error: Overflow");
    }//terminates push method
    public void pop() throws StackException
    {
        if(!isEmpty())//current stack is not empty
            --topValue;
        else //stack is empty
            throw new StackException("Error: Underflow");
    }//terminates pop method
    public boolean isEmpty()
    {
        return topValue==-1;
    }//terminates isEmpty method
    public E top() throws StackException
    {
        if(!isEmpty())//stack is not empty
            return (E)Info[topValue];
        else //stack is empty
            throw new StackException("Error: Underflow");
    }//terminates top method
    //declare instance variables    
    final int ArraySize=10;
    private Object Info[]=new Object[ArraySize];
    private int topValue;

//begins coding for the StackException class
class StackException extends RuntimeException
{
    //constructor
    public StackException(String str)
    {
        super(str);
    }//terminates text of constructor
}//terminates text of StackException class

//method to convert from infix to postfix notation
public static String InToPost(String infixString)
{
    //operator stack initialized
    objArrayStack<Character> operatorStack = new objArrayStack<Character>();
    //postfix string initialized as empty
    String postfixString = " ";
    //scan infix string and take appropriate action
    for(int index = 0; index < infixString.length(); ++index)
    {
        char chValue = infixString.charAt(index);
        if(chValue == '(')
            operatorStack.push('(');
        else if(chValue == ')')
        {
            Character oper = operatorStack.top();
            while(!(oper.equals('(')) && !(operatorStack.isEmpty()))
            {
                postfixString += oper.charValue();
                operatorStack.pop();
                oper = operatorStack.top();
            }//end while loop
                operatorStack.pop();
    }//end else if  
    else if(chValue == '+' || chValue == '-')
    {
        if(operatorStack.isEmpty()) //operatorStack is empty
            operatorStack.push(chValue);
        else //current operatorStack is not empty
        {
            Character oper = operatorStack.top();
            while(!(operatorStack.isEmpty() || oper.equals(new Character('(')) || oper.equals(new Character(')'))))
            {
                operatorStack.pop();
                postfixString += oper.charValue();
            }//ends while loop
            operatorStack.push(chValue);
        }//end else 
    }//end else if
    else if(chValue == '*' || chValue == '/')
    {
        if(operatorStack.isEmpty())
            operatorStack.push(chValue);
        else
        {
            Character oper = operatorStack.top();
            while(!oper.equals(new Character('+')) && !oper.equals(new Character('-')) && !operatorStack.isEmpty())
            {
                operatorStack.pop();
                postfixString += oper.charValue();
            }//end while loop
            operatorStack.push(chValue);
        }//end else
    }//end else if
    else
        postfixString += chValue;
    }//end for loop
    while(!operatorStack.isEmpty())
    {
        Character oper = operatorStack.top();
        if(!oper.equals(new Character('(')))
        {
            operatorStack.pop();
            postfixString += oper.charValue();
        }//end if
    }//end while
    return postfixString ;
}//terminates text of InToPost method

public static void main(String[]args)
{
    objArrayStack mystack = new objArrayStack();
    System.out.println("Enter a string");
    Scanner scan = new Scanner(System.in);
    scan.nextLine();
    String str = scan.nextLine();
    InToPost(str); 
}//terminates text of main method
}//terminates text of objArrayStack class

Use System.out.println("Your message") to print debugging messages about your input string and the value of every variable. First, ensure that the string is received from the scanner. After, look in the code of the stack.

scan.nextLine();
String str = scan.nextLine();

This is what causes the problem. You are already moving your scanner past the line read. Remove the first scanner.nextLine();
Read the Scanner docs here for more details.

u need to implement the stack
then do precedence with switch cases
ill give more info once i get home, but at least show some code that you wrote not the code from your resource material form CD

u need to implement the stack
then do precedence with switch cases
ill give more info once i get home, but at least show some code that you wrote not the code from your resource material form CD

I implemented the stack interface and the class containing all of the methods(pop, push, etc.) and I'm pretty sure there are no errors there. I wrote this code myself, I didn't copy it from a CD or website. Also, I know for a fact that converting from infix to postfix can be done without using a switch statement. Thanks for the reply though.

u need to implement the stack
then do precedence with switch cases
ill give more info once i get home, but at least show some code that you wrote not the code from your resource material form CD

Why is that, that you believe he copied the code ?

@OP : Read my prvious post I've underlined the problem there.

Thanks for backing me up, verruckt24. It is good to see that not everyone in this forum is so cynical and suspicious. I made some ajustments to my program and got it to work. Thanks for your help.

Has your query been solved, if yes then please mark the thread so, so people don't keep posting here for ages :)

If anyone needs help with this particular problem (converting infix to postfix and evaluating), send me a message. I have a working version of the program and I'd be glad to help.

Instead of offering them the program, let them learn the way you did by, putting pieces together and asking wherever he's stuck. Plus it would certainly be of more benefit to all learners if it is kept on the forum. Not that he cannot PM you asking for help, but keeping it on the forum is always better for the community.

Also if you feel you have a piece of code worth sharing you can always add to the code snippets on the forum. This way the work of programming has a larger audience and user base.

Sorry, I didn't mean that I would just give them the program. I was just saying that I have it correctly completed if anyone needs help. I respect the forum rules and would never go against the policy. I know that it is important for fellow viewers to solve their own problems by themselves with just a liitle help from the community. Sorry once again for the implications of my previous post.

HI!...I thinked I badly needed ur help..I'm also working w/ that problem and I want to know what's wrong w/ my codes..
Here is my code:

import java.util.*;
import java.lang.String.*;
import java.lang.Object;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;


public class InToPre
{
  private Stack operators = new Stack();
  private Stack operands = new Stack();
  private char[] chars = null;

  public InToPre(char[] chars)
  {
     this.chars = chars;
  }

  private  boolean isValid()
  {
     boolean isValid = true;
     // characters in the string can be math symbols '+ - * / ' or be space
     // or
     // can be paranthises '(' or ')'
     // can be a digit
     for(int i =0; i<chars.length;i++)
     {
        if (Character.isLetter(chars[i]) == true) 
        {
           isValid = false;
           break;
        }

        if (Character.isDigit(chars[i]) == true) continue;
        if (Character.isSpaceChar(chars[i]) == true) continue;
        if (chars[i] == '+') continue;
        if (chars[i] == '-') continue;
        if (chars[i] == '/') continue;
        if (chars[i] == ' ') continue;
        if (chars[i] == '*') continue;
        if (chars[i] == '(') continue;
        if (chars[i] == ')') continue;
        isValid = false;
     }

     return isValid;
  }

  public String convert() throws NotValidInFixException 
  {
     String  operand1, operand2, operatorTemp, strTemp, preFixStr;

     if (isValid() == false)
     {
        throw new NotValidInFixException(new String(chars)+ " is not a valid Infix        

        expression");
     }

     for (int i =0 ;i< chars.length; i++)   
     {
        switch (chars[i])
        {
          // case ' ': break; // if char is space just continue
           case '(': break; // if char is left Parenthesis continue
           case '0': // if char is a number push number on to operands stack
           case '1':
           case '2':
           case '3':
           case '4':
           case '5':
           case '6':
           case '7':
           case '8':
           case '9':
              operands.push(Character.toString(chars[i])+" ");
              break;
           case '+': // if char is a math symbol push char to operators stack
           case '-':
           case '*':
           case '/':
           case ' ':
              operators.push(Character.toString(chars[i])+" ");
              break;
           case ')':
              operand1 = Stack.pop;
              operand2 = Stack.pop;
              operatorTemp = Stack.pop;
              strTemp = operatorTemp + operand2 + operand1;
              operands.push(strTemp);
              break;

        }
     }
     return operands.pop();
  }


//The exception class:

class NotValidInFixException extends Exception
{
  NotValidInFixException(String s)
  {
     super(s);
  }
}

  public static void main(String args[]) throws IOException, NotValidInFixException
  {
     System.out.print("Enter Infix : ");
     String input = getInput();
     char[] chars = input.toCharArray();
     InToPre itp = new InToPre(chars);
     String prefix = itp.convert();
     System.out.println(prefix);
  }

  public static String getInput() throws IOException 
  {
     BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
     return read.readLine();
  }

} //end of InToPre

my error is in pop method...

operand1 = Stack.pop;
operand2 = Stack.pop;
operatorTemp = Stack.pop;

how can I debug this error???I hope you can help me...
THANK YOU IN ADVANCE

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.