Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Stack<T> {
- private int stackPos;
- private T[] stack;
- public Stack(int size) {
- this.stackPos = -1;
- this.stack = (T[]) new Object[size];
- }
- public void push(T value) {
- if (this.stackPos < this.stack.length - 1) {
- this.stack[++stackPos] = value;
- }
- }
- public T pop() {
- if (this.isEmpty()) {
- return null;
- }
- return this.stack[stackPos--];
- }
- public int length() {
- if (this.isEmpty()) {
- return 0;
- }
- return this.stackPos + 1;
- }
- public T head() {
- if (this.isEmpty()) {
- return null;
- }
- return this.stack[stackPos];
- }
- public boolean isEmpty() {
- return this.stackPos == -1;
- }
- public void print() {
- if(this.isEmpty()) {
- System.out.println("Pilha vazia..");
- }else{
- for(int i = stackPos; i >= 0; i--){
- System.out.println(stack[i]);
- }
- }
- }
- }
- public class NPR {
- public static int operate(String operation, int left, int right) {
- switch (operation) {
- case "+": return left + right;
- case "-": return left - right;
- case "*": return left * right;
- case "/":
- if (right == 0) {
- System.out.println("ERR: Não é possível dividir por zero");
- return left;
- }
- return left / right;
- default: return left;
- }
- }
- public static int parseOperation(String operation, Stack<Integer> stack) {
- int result = (stack.isEmpty()) ? 0 : stack.pop();
- if (!stack.isEmpty()) {
- result = operate(operation, stack.pop(), result);
- }
- return result;
- }
- public static boolean isInteger(String input) {
- if (input == null) return false;
- try {
- Integer.parseInt(input);
- } catch (NumberFormatException ex) {
- return false;
- }
- return true;
- }
- public static boolean isOperation(String input) {
- if (input == null) return false;
- return input.equals("+") || input.equals("-") || input.equals("*") || input.equals("/");
- }
- public static void main(String[] args) {
- Scanner reader = new Scanner(System.in);
- Stack<Integer> stack = new Stack<Integer>(30);
- System.out.println("Digite a operação (s para sair)");
- String input = "";
- while (!input.equals("s")) {
- input = reader.nextLine();
- if (isInteger(input)) {
- stack.push(Integer.parseInt(input));
- } else if (isOperation(input)) {
- int current = parseOperation(input, stack);
- if (stack.length() == 0) {
- System.out.println(">> " + current);
- } else {
- System.out.println("> " + current);
- }
- stack.push(current);
- }
- }
- reader.close();
- }
- }
Add Comment
Please, Sign In to add comment