Expression Calculator - Expression break problem

Asked

Viewed 566 times

6

I’m going to college and I have to do an expression calculator on java, that is, basically if you write (5+5)/2 or something like that, it has to give you the right result.

I had no problems with the use of batteries and queues, but I came across a problem when breaking my expression. Follow the method and the Exception that occurred to me:

private static String[] quebraExressao(String expressao)
{
    expressao = expressao.replaceAll(" ", "").replaceAll("", " ");
            String regex = "[0-9]";
            String[] elementos = expressao.split(" ");
            String[] elementos_retorno = new String[elementos.length];
            int j = 0;

            for (int i =0; i < elementos.length; i++)
            {
                if (elementos[i].matches(regex))
                {
                    if (elementos[i+1].matches(regex))
                    {
                        elementos_retorno[j] = elementos[i] + elementos[i+1];
                        i++;
                    }
                    else 
                    {
                        elementos_retorno[j] = elementos[i];
                    }
                }
                else 
                {
                    elementos_retorno[j] = elementos[i];
                }

                j++;
            }

    return elementos_retorno;
}

And finally I got this Exception

Enter the expression:5+5
Expression: 5 + 5

java.lang.Arrayindexoutofboundsexception: 4 0.0 at calculadorapoo.Expressao.quebraExressao(Expresso.java:199) at calculadorapoo.Expressao.calcular(Expresso.java:63) at at calculadorapoo.Expressao.calcular calculator.CalculoPolones.calculates(Calculopolones.java:14) at calculator.CalculationPOO.main(calculator.java:18) BUILT SUCCESSFULLY (total time: 5 seconds)

I am using netbeans to make my program and didn’t quite understand where my array popped.

I would like to know the best possible solution, I am learning java for a short time. If you need the rest of the program, I can post here. Thank you.

EDITED: I managed to solve the problem, but now I have Nullpointer problem. Follow the code and the error:

 public Double calcular() throws Exception 
{
int tamanhoFila = this.expressao.trim().length();
Fila fila = new Fila<>(tamanhoFila);
Pilha pilha = new Pilha<>(tamanhoFila);
String regex = "[0-9]";

String[] elementos = quebraExressao(this.expressao.trim());
for (String token : elementos)
{
        if (!token.equals(""))
        {
    if (token.matches(regex))   // se for numero
    {
                fila.emfila(token);
    }
    else    // se for operador
    {
                if (pilha.isVazia())
                {
        pilha.insere(token);
                }
                else 
                {
        String ultimoOperador = pilha.getUltimoElemento().toString();

        if (Tabela.devoDesempilhar(ultimoOperador.charAt(0), token.charAt(0)))
        {
                        if (token.equals(")"))
                        {
            while(!pilha.getUltimoElemento().equals("("))
            {
                                fila.emfila(pilha.retira());
            }
                                pilha.retira(); // para retirar o (
                        }
                        else 
                        {
            while(Tabela.devoDesempilhar(ultimoOperador.charAt(0), token.charAt(0)))
            {
                                fila.emfila(pilha.retira());
                                if (pilha.isVazia())
                                {
                pilha.insere(token);
                break;
                                }
                                else 
                ultimoOperador = pilha.getUltimoElemento().toString();
            }
                        }
        }
        else 
        {
                        pilha.insere(token);
        }
                }

    }
        }
}

Apparently it occurred in two places; I still do not know if it is because of the first one, but I will put the other method.

public double calcula(String expressao)
{
double resultado = 0.0;

Expressao exp = new Expressao(expressao);

try 
    {
System.out.println("Expressao: " + expressao);
resultado = exp.calcular();

} 
    catch (Exception e) 
{
        // TODO Auto-generated catch block
        e.printStackTrace();
}

return resultado;
}

Here comes the NULLPOINTER and its locality

Enter the expression:5+5
Expression: 5 + 5 java.lang.Nullpointerexception 0.0 calculated at.Expressao.calculate(Expression.java:66) calculated at.CalculoPolones.calculates(Calculopolones.java:14) At calculator.CalculationPOO.main(Calculadorapoo.java:18) SUCCESSFULLY BUILT (total time: 2 seconds)

  • I still do not know the problem, but already I say that your array has not burst, the exception ArrayIndexOutOfBoundsException occurs when you try to access a non-existent index.

  • I believe on the line if (elementos[i+1].matches(regex)) the index i+1 may not exist. Prior to such verification, check whether i+1 < elementos.length. Maybe that alone will solve your problem.

  • Then just put if(i+1 < elements.length) and after that put the rest?

  • Your regex only checks if the first letter is digit. Better put String regex = "[0-9]+";, but only applies if the calculator receives numbers with more than one digit.

  • Thank you John, the calculator does receive more than two digits!

  • Where is line 66? It is the cause of nullpointer.

  • Diego F to Line 66 is the start of the for

Show 2 more comments

1 answer

1

A colleague of mine made a calculator in Java and used a different way than yours. He used a method called "Eval" that turns a string into executable code for Javascript. I’ll show you an example:

public static void main(String[] args) 
{
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");

    String teste = "print((5-2) * 3);";
    try 
    {
     engine.eval(teste);
    } 
    catch (ScriptException e)
    {
     e.printStackTrace();
 }

The result will appear on the console 9.

I don’t know if that answers your question, but I hope I’ve helped.

  • So, I know about the One , but I was not allowed to use =/

  • I see, what a pity.

  • But in case you can help me, I have Nullpointer error in my for xD

  • What is line 66 of the code?

  • for (String token : elements)

  • Well, I don’t know if that’s it, but try the following: for(int i = 0; i < elements.lenght; i++), then you’d have to change the rest of your program’s logic.

  • To not need to change the rest of the code you can do so after the for suggested by @Douglas: for(int i = 0; i < elementos.lenght; i++) { String token = elementos[i]; }

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.