-4
Hello stackoverflow friends, I’m finishing my calculator and I’m having nullpointer problems, I’m new in java and do not know how to change the logic to solve the problem, there goes the code I’m having problems
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);
}
}
}
}
}
more precisely on that line
for (String token : elementos)
how to change the logic so that it solves the Null Pointer problem?
On request here is the method Breakexpression:
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 (i+1 < elementos.length)
{
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;
}
If I put the code can give a better view?
– Anddiy
Yes , puts the breakExpressao
– Augusto Porto
I will edit the post
– Anddiy
I added the method
– Anddiy
That . replaceAll is just to take out the blanks ? If it’s the first replaceAll already does that, you wouldn’t need the second
– Augusto Porto
Unfortunately it was not I who did this part , but I was told that it is not just for this =/
– Anddiy
Well, since I don’t know if you really need the second replaceAll, in my view when the code arrives in that split, it wouldn’t split , because it wouldn’t find the white space that you ask it to use as a delimiter. In this case , I think you should debug this function , would put a breakpoint at the beginning of the function and would see the values assigned to the variables to see if they are within the expected. Your problem is in function logic, the rest is debugging and finding the error.
– Augusto Porto