Skip to content

Instantly share code, notes, and snippets.

@divanibarbosa
Last active April 26, 2023 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divanibarbosa/ed381aa30e1280ad1e794cf52e065be8 to your computer and use it in GitHub Desktop.
Save divanibarbosa/ed381aa30e1280ad1e794cf52e065be8 to your computer and use it in GitHub Desktop.
Calculadora em notação posfixa (NPR) Lukasiewicz - Java
/* 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