How to use an arithmetic signal to separate one value from the other in a Mathematical String? [closed]

0

I'm developing a calculator which, at the end of the code, executes a function called mostrarResultado() , this function gets the String of campoTexto of the screen, Ex :( "2 + 3"), and I want any either the operator (which is stored inside an operation variable), or the character that separates a String from the other. However, when executing the code, a Fatal Exception occurs, in line 3 of the code that follows, of the function implemented to date. Thanks in advance.

    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));
}
    
asked by anonymous 01.02.2016 / 22:00

1 answer

2

You need to do 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 split by it.

Example:

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

if (texto.contains("+"))
  valores = texto.split("+");
else if (texto.contains("-"))
  valores = texto.split("-");
    
01.02.2016 / 22:12