Duvida Notação Polonesa Reversa

0 respostas
F

9 6 - 4 8 + *

Urgente....

alguem pode me ajudar a corrigir esse erro, meu programa calcula todos de mais calculos, mas esse não

9 6 - 4 8 + *

import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

public class Calculadora {

	private static boolean checkStr(String str) {

		String erro = "";
		String[] lee = str.split(" ");
				
		Pattern regex = Pattern.compile("[\\/\\*\\+-]");

		if (lee.length < 3) {
			erro += "Entrada incorreta de dados.\n";
		} else {
			for (int i = 0; i < lee.length; i++) {

				if (i < 2) {
					String[] numb = lee[i].split("/");
					String calcDiv = "";
					if (numb.length == 2) {
						Double val1 = new Double(numb[0]);
						Double val2 = new Double(numb[1]);
						calcDiv = Double.toString(val1.doubleValue() / val2.doubleValue());
						if (isNumerico(calcDiv)) {
							lee[i] = calcDiv;
						} else {
							erro += "Divisão por zero.\n";
						}
					} else {
						try {
							Double.parseDouble(lee[i]);
						} catch (NumberFormatException e) {
							erro += "Os dois primeiros valores devem ser numéricos e não devem dividir por zero.\n";
						}
					}
				} else if (i > 2 || i < (lee.length + 1)) {
					if (checarDivizaoZero(lee)) {
						erro += "Divisão por zero.\n";
					}

					if ((i % 2) == 0) {
						Matcher matcher = regex.matcher(lee[i].toString());

						if (!matcher.matches()) {
							erro += "Na posição " + (i + 1) + "(" + lee[i]
									+ ") deve conter um operador aritimético.\n";
						}
					} else {
						String[] numb = lee[i].split("/");
						String calcDiv = "";
						if (numb.length == 2) {
							Double val1 = new Double(numb[0]);
							Double val2 = new Double(numb[1]);
							calcDiv = Double.toString(val1.doubleValue() / val2.doubleValue());
							if (isNumerico(calcDiv)) {
								lee[i] = calcDiv;
							} else {
								erro += "Divisão por zero (" + lee[i] + ").\n";
							}
						} else {
							try {
								Double.parseDouble(lee[i]);
							} catch (NumberFormatException e) {
								erro += "Na posição " + (i + 1) + "(" + lee[i]
										+ ") deve conter um valor numérico.\n";
							}
						}

					}
				}

				if (i == lee.length - 1) {
					Matcher matcher = regex.matcher(lee[i].toString());

					if (!matcher.matches()) {
						erro += "Adicione um operador aritmético na última posição.\n";
					}
				}

			}
		}

		if (!erro.equals("")) {
			JOptionPane
					.showMessageDialog(null, erro, "Erro encontrado", JOptionPane.ERROR_MESSAGE);
			return false;
		} else {
			leeGlobal = lee;
			return true;
		}

	}

	//checa para ver se a divisão não é por zero
	private static boolean checarDivizaoZero(String[] lee) {

		boolean result = false;

		for (int i = 0; i < lee.length; i++) {
			if (lee[i].equals("0") && lee[i + 1].equals("/")) {
				result = true;
				break;
			} else {
				result = false;
			}
		}
		return result;
	}

	//verifica se é número
	private static boolean isNumerico(String str) {

		Pattern regex = Pattern.compile("-?([0-9]|\\.)+?");
		Matcher matcher = regex.matcher(str);
		if (!matcher.matches()) {
			return false;
		} else {
			return true;
		}

	}

	//calcula expressão
	private static double calculaExp(Stack<String> lee) {

		double resultado = 0.0;
		for (int i = 0; i < lee.size() -1; i++) {
			if (i == 0) {
				resultado = new Double(lee.get(i).toString()).doubleValue();
				i++;
			}
			if (lee.get(i).toString().equals("/")) {
				resultado /=  new Double(lee.get(i + 1).toString()).doubleValue();
			} else if (lee.get(i).toString().equals("*")) {
				resultado *=  new Double(lee.get(i + 1).toString()).doubleValue();
			} else if (lee.get(i).toString().equals("+")) {
				resultado += new Double(lee.get(i + 1).toString()).doubleValue();
			} else if (lee.get(i).toString().equals("-")) {
				resultado -= new Double(lee.get(i + 1).toString()).doubleValue();
			}
			i++;
		}

		return resultado;
	}

	//construtor
	private static Stack<String> sorLee(String[] lee) {

		Stack<String> newLee = new Stack<String>();

		for (int i = 0; i < lee.length - 1; i++) {
			if (i == 0) {
				newLee.push(lee[i]);
			}
			i += 2;
			newLee.push(lee[i]);
			i--;
			newLee.push(lee[i]);
		}

		return newLee;
	}
	
	//CalculadoraApp
	public static void main(String[] args) {

		boolean verify = false;
		String str = "";
		int escolha = JOptionPane.YES_OPTION;

		while (escolha == JOptionPane.YES_OPTION) {

			while (!verify) {
				str = JOptionPane.showInputDialog("Informe uma expressão para ser calculada:", str);
				try {
					str.toString();
				} catch (NullPointerException e) {
					System.exit(0);
				}

				verify = checkStr(str);
			}

			JOptionPane.showMessageDialog(null, "Resultado: "
					+ calculaExp(sorLee(leeGlobal)), "Resultado",
					JOptionPane.INFORMATION_MESSAGE);

			String[] opcoes = { "Sim", "Não" };
			escolha = JOptionPane.showOptionDialog(null, "Calcular outra expressão?", "SAIR",
					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opcoes, null);
			verify = false;
			str = "";

		}
		System.exit(0);
	}

	public static String[] leeGlobal;
}
Criado 22 de abril de 2009
Respostas 0
Participantes 1