Last active
April 26, 2023 00:32
-
-
Save divanibarbosa/ed381aa30e1280ad1e794cf52e065be8 to your computer and use it in GitHub Desktop.
Calculadora em notação posfixa (NPR) Lukasiewicz - Java
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
/* Criado por: profa. Divani Barbosa Gavinier | |
Curriculo Lattes: http://lattes.cnpq.br/8503400830635447 | |
divanibarbosa@gmail.com | |
*/ | |
import java.io.*; | |
import java.lang.*; | |
class No { | |
public int item; | |
public No ant; | |
} | |
class PilhaSE { | |
private No topo; | |
public PilhaSE() { topo = null; } | |
public boolean empty() { return (topo == null); } | |
public int top() { return topo.item; } | |
public void pop() { if (!empty()) topo = topo.ant; } | |
public void push(int valor) { | |
No novo = new No(); | |
novo.item = valor; | |
novo.ant = topo; | |
topo = novo; | |
} | |
} | |
class PilhaExpressoes { | |
public static void main(String[] args) throws IOException { | |
PilhaSE p = new PilhaSE(); | |
int arg1, arg2; | |
char c; | |
System.out.println("Calculadora notação pos-fixa"); | |
System.out.println(" Exemplo de uso:\n 5 9 + 2 * 6 5 * + "); | |
System.out.print("Informe sua expressao:\n "); | |
String s = lerStr(); | |
for (int i=0; i<s.length(); i++) { | |
c = s.charAt(i); | |
if (Character.isDigit(c)) | |
p.push(Character.digit(c,10)); | |
else if(c=='+') { | |
arg1 = p.top(); p.pop(); | |
arg2 = p.top(); p.pop(); | |
p.push(arg1+arg2); | |
} | |
else if(c=='*') { | |
arg1 = p.top(); p.pop(); | |
arg2 = p.top(); p.pop(); | |
p.push(arg1*arg2); | |
} | |
else if(c=='-') { | |
arg1 = p.top(); p.pop(); | |
arg2 = p.top(); p.pop(); | |
p.push(arg1-arg2); | |
} | |
else if(c=='/') { | |
arg1 = p.top(); p.pop(); | |
arg2 = p.top(); p.pop(); | |
p.push(arg1/arg2); | |
} | |
else if(c=='^') { | |
arg1 = p.top(); p.pop(); | |
arg2 = p.top(); p.pop(); | |
p.push((int) Math.pow(arg1,arg2)); | |
} | |
} | |
System.out.println("Resposta = " + p.top()); | |
p.pop(); | |
} | |
public static String lerStr() throws IOException { | |
InputStreamReader isr = new InputStreamReader(System.in); | |
BufferedReader br = new BufferedReader(isr); | |
String s = br.readLine(); | |
return s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment