Skip to content

Instantly share code, notes, and snippets.

@jmlon
Created February 13, 2020 19:54
Show Gist options
  • Save jmlon/82f5b2da8ce623539e10eed78f19f1d8 to your computer and use it in GitHub Desktop.
Save jmlon/82f5b2da8ce623539e10eed78f19f1d8 to your computer and use it in GitHub Desktop.
Evaluación de expresiones en notación RPN
package edu.upb.estalg.Estructuras;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class EvaluadorRPN {
public static void main(String[] args) {
Stack<Double> pila = new Stack<>();
while (StdIn.hasNextLine()) {
try {
String input = StdIn.readString();
if (input.equals("+")) {
double d = pila.pop()+pila.pop();
pila.push(d);
StdOut.println(d);
}
else if (input.equals("-")) {
double d = -pila.pop()+pila.pop();
pila.push(d);
StdOut.println(d);
}
else if (input.equals("*")) {
double d = pila.pop()*pila.pop();
pila.push(d);
StdOut.println(d);
}
else if (input.equals("/")) {
double d = 1.0/pila.pop()*pila.pop();
pila.push(d);
StdOut.println(d);
}
else {
try {
double d = Double.parseDouble(input);
pila.push(d);
}
catch(NumberFormatException nfe) {
StdOut.println("Entrada no valida");
}
}
}
catch(NoSuchElementException nse) {
StdOut.println("Programa terminado");
}
}
StdOut.println("Resultado: "+pila.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment