In: Computer Science
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted to a file of your choice using a stack with one space between operators and variables ( one letter variables) and/or constants (one digit constants).
A program in Java programmig language to convert infix expression into post-fix expression.
import java.util.*;
import java.io.*;
class Conversion
{
static String infixToPostfix(String expInfix) //method to create
infix to postfix
{
String expPostfix = new String("");
Stack <Character> stack = new Stack<>();
for(int i = 0; i < expInfix.length(); ++i)
{
char ch = expInfix.charAt(i);
if (ch == ' ')
{
continue;
}
if (Character.isLetterOrDigit(ch))
expPostfix += ch;
else if (ch == '(')
stack.push(ch);
else if (ch == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
expPostfix += stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return "The expresiion is Invalid";
else
stack.pop();
}
else
{
while (!stack.isEmpty() && Prec(ch) <=
Prec(stack.peek()))
{
if(stack.peek() == '(')
return "The expression is invalid";
expPostfix += stack.pop();
}
stack.push(ch);
}
}
while (!stack.isEmpty())
{
if(stack.peek() == '(')
return "The expression is invalid";
expPostfix += stack.pop();
}
return expPostfix;
}
static int Prec(char ch)
{
switch (ch)
{
case '-':
case '+':
return 1;
case '/':
case '*':
return 2;
case '%':
return 3;
}
return -1;
}
}
public class Test //test class
{
public static void main(String[] args)
{
try
{
Conversion con = new Conversion();
String exp = "(A + B) * C";
String inputExp = "";
FileReader fr=new FileReader("D:\\input.txt"); //read file
int i;
while((i=fr.read())!=-1)
inputExp = inputExp + (char)i;
fr.close();
FileWriter fw=new FileWriter("D:\\output.txt"); //write file
//fw.write(con.infixToPostfix(exp));
fw.write(con.infixToPostfix(inputExp));
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("\nFile created successfully.");
}
}
OUTPUT:
File created successfully.
Content of output.txt file:
AB+C*