Skip to content

Instantly share code, notes, and snippets.

@iruvingu
Last active March 6, 2018 02:36
Show Gist options
  • Save iruvingu/fb1a5233fb36d52897a1d846ab1eda76 to your computer and use it in GitHub Desktop.
Save iruvingu/fb1a5233fb36d52897a1d846ab1eda76 to your computer and use it in GitHub Desktop.
This code convert Infix notation to Postfix notation strings for a calculator. You can use whatever way to introduces the Strings but this time I introduce it manually. Hope this can work for you! //Unfortunately this doesn´t validate some facts of a calculator yet.
import java.util.Stack;
public class InfijoAPosfijo {
public static void main(String[] args) {
String myString = "2.3 + 1.2 * ( ( 3.2 + 12 ) - 12 )"; //You can put your entrance here
String[] expression = myString.split(" ");
String postfix = inf_posf(expression);
System.out.println(postfix);
}
public static String inf_posf(String[] exp) {
Stack<String> pila = new Stack<String>();
String postfix = ""; // Inicializar el String postfijo final
for (int i=0;i<exp.length;i++){ //Buscar en todos los elementos del array exp
if (!esOperando(exp[i]) && !esParentesisDer(exp[i])){
while (!pila.empty()
&& !pila.peek().equals("(")
&& tieneMayorPrioridad(pila.peek(), exp[i])){
postfix += " " + pila.peek();
pila.pop();
}
pila.push(exp[i]);
}
else if (esOperando(exp[i])) {
postfix += " " + exp[i];
}
else if (esParentesisDer(exp[i])){
while (!pila.empty() && !pila.peek().equals("(")){
postfix += " " + pila.peek(); pila.pop();
}
pila.pop();
}
}
while (!pila.empty()){
postfix += " " + pila.peek(); pila.pop();
}
return postfix;
}
public static boolean esParentesisDer(String Parent){
String parentesis = ")";
if (Parent.compareTo(parentesis) == 0)
return true;
else return false;
}
public static boolean esOperando(String Op){
//Float flotante = new Float(Op);
try
{
Float.parseFloat(Op);
return true;
}
catch(NumberFormatException e)
{
//not a Float
return false;
}
}
public static boolean tieneMayorPrioridad(String op1, String op2){
int op1Weight = getPesoOperador(op1);
int op2Weight = getPesoOperador(op2);
if ((op1Weight == op2Weight) && (op1Weight != 3)){
return true;
}else if ((op1Weight == 3) && (op2Weight == 3)) {
return false;
}
return op1Weight>op2Weight? true : false;
}
public static int getPesoOperador(String op){
int weight = -1;
switch (op)
{
case "+":
case "-":
weight = 1;
break;
case "*":
case "/":
case "sin":
case "cos":
case "tan":
case "cot":
case "sec":
case "csc":
weight = 2;
break;
case "^":
weight = 3;
break;
}
return weight;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment