I am having trouble getting my infix converter to work properly, I am kinda a newbee at programing and this is really killing me. I havent yet tried to incorporate parentheses yet but that is my next step.
Code:
package infix_postfix;
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack stack = new Stack(); //uses java built in stack
String input_string;
Scanner input = new Scanner(System.in);
int order=0;
String temp="";
String out="";
System.out.println("Infix Converter: V.1.0 Kelly Qualls");
System.out.println("This program is designed to take binary operators"
+ " including parenthetical math to be able to show the postfix"
+ " equivilent");
System.out.println("Please enter the infix notation:>");
input_string=input.nextLine();
// String delims = "[+\\-*/\\^ ]+"; // so the delimiters are: + - * / ^ space
String[] tokens = input_string.split("(?<=[ +\\-*/\\^ ]+)");
stack.push("out");
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].equals("+"))
{
temp=(String)stack.peek();
if(temp.equals("out"))
{
stack.push("+");
}
else{
if(temp.equals("*")||temp.equals("/"))
{
out += stack.pop();
stack.push("+");
}
else
stack.push("+");
}
}
else if(tokens[i].equals("-"))
{
temp=(String)stack.peek();
if(temp.equals("out"))
{
stack.push("-");
}
else{
if(temp.equals("*")||temp.equals("/"))
{
out += stack.pop();
stack.push("-");
}
else
stack.push("-");
}
}
else if(tokens[i].equals("/"))
{
temp=(String)stack.peek();
if(temp.equals("out"))
{
stack.push("/");
}
else{
if(temp.equals("*")||temp.equals("/"))
{
out += stack.pop();
stack.push("/");
}
else
stack.push("/");
}
}
else if(tokens[i].equals("*"))
{
temp=(String)stack.peek();
if(temp.equals("out"))
{
stack.push("*");
}
else{
if(temp.equals("*")||temp.equals("/"))
{
out += stack.pop();
stack.push("*");
}
else
stack.push("*");
}
}
else {
out += tokens[i];
temp= (String)stack.peek();
}
}
while(!temp.equals("out"))
{
out+=stack.pop();
temp=(String)stack.peek();
}
// order++;
System.out.println(out);
}
}
Comment