How to use an arithmetic signal to separate one value from another in a mathematical string?

Asked

Viewed 129 times

0

I’m developing a calculator that, at the end of the code, performs a function called mostrarResultado(), this function receives the campoTexto from the screen, Ex:("2+3"), and I want whatever the operator (which is stored inside an operation variable) to be the character that separates one String from the other. However, when executing the code, a Fatal Exception, in line 3 of the code below, of the function implemented so far. I thank you.

    public void mostrarResultado(){
    String texto =  campoTexto.getText().toString();

    String[] valores = texto.split(operacao);

    float numA = Float.parseFloat(valores[0]);
    float numB = Float.parseFloat(valores[1]);
    float result = 0;

    switch(operacao) {
        case "+":
            result = numA + numB;
            break;
        case "-":
            result = numA - numB;
            break;
        case "*":
            result = numA * numB;
            break;
        case "/":
            result = numA / numB;
            break;
    }

    campoTexto.setText(String.valueOf(result));
}
  • 1

    Where does this variable come from operação?

  • It is a global variable that is used in another function as well. This other function is the one that stores the operator value within the operation variable.

  • And what’s in it. You have to put all the information you need to understand the code. You must [Dit] the question to put everything that is relevant.

  • @Brunotoledo, please indicate if my answer helps anything, because really the way your question is getting complicated help. If my answer does not answer, please signal so I can delete it. About your code, I saw that you changed the content of Split. Before it had a string called "operation", now it has a variable called operation. If you don’t put more code and indicate how you get this operation, it gets very complicated to help you.

1 answer

2


You need to do the split by the operator (+,-,*,/) and not by String operacao as shown in your code.

For this, a simple approach (since you are learning), would be to check if the String contains the operator, if it contains you do the split by it.

Example:

String texto =  campoTexto.getText().toString(); 
String[] valores;

if (texto.contains("+"))
  valores = texto.split("+");
else if (texto.contains("-"))
  valores = texto.split("-");

Browser other questions tagged

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