Created
February 13, 2020 19:54
-
-
Save jmlon/82f5b2da8ce623539e10eed78f19f1d8 to your computer and use it in GitHub Desktop.
Evaluación de expresiones en notación RPN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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