I searched for this topic first, because it is pretty popular, but I didn't find much to help. What I was instructed to do was convert a prefix expression to a postfix expression. I have to use a stack and a queue, which is different than many other threads about this topic. Another thing that is different is that my expressions are purely variables(ie +*A B / C D). I made a little progress on my own, and I don't want everyone to solve it for me, but help would be extremely appreciated.
I am reading the expressions from a file. I also put the postfix operands in the queue, and the operators in the stack. I get stuck when it is time to use the information. This is what I planned to do next:
if an operator is followed by 2 items that are operands, pop them and then pop the operator, else push into stack.
However, I have no clue as to do that; even if I am going in the correct direction.
If you stopped by, thanks, if you helped, thanks, if not, thanks anyway.
What I have so far:
import java.io.*;
import java.util.*;
public class lab8
{
//Nodes
static String strToken;
static boolean expressionOk;
public static void main(String[] args)
//throws FileNotFoundException
{
//declare the operators stack
StackClass<String> postfixStack =
new StackClass<String>(100);
//declare the expression queue
QueueClass<String> postfixQueue =
new QueueClass<String>(100);
//Try for error handling
try
{
//File operations
Scanner inputStream = new
Scanner(new FileReader("c:\\Prefix.txt"));
PrintWriter outfile = new
PrintWriter("c:\\Postfix.txt");
//While loop for file operations
while (inputStream.hasNext())
{
postfixStack.initializeStack();
expressionOk = true;
}//end while
outfile.close();
}
//Catch for error handling
catch (FileNotFoundException fnfe)
{
System.out.println(fnfe.toString());
}
}
public void evaluateExpression() throws FileNotFoundException
{
//declare the operators stack
StackClass<String> postfixStack =
new StackClass<String>(100);
//declare the expression queue
QueueClass<String> postfixQueue =
new QueueClass<String>(100);
Scanner inFile = new Scanner(new FileReader("c:\\Prefix.txt"));
while (inFile.hasNext())
{
String op;
op = inFile.next();
//Switch to put in either stack or queue
//Because operator, goes in stack, else queue
switch(op.charAt(0))
{
case '+':
postfixStack.push(op);
break;
case '-':
postfixStack.push(op);
break;
case '*':
postfixStack.push(op);
break;
case '/':
postfixStack.push(op);
break;
default:
postfixQueue.addQueue(op);
}//end switch
}//end while
}//end evaluateExpression
}//end project