Java - parseInt ()

0
public void OK(View v)
{
    EditText editTextView = (EditText) findViewById(R.id.editTextView);
    String myEditValue = editTextView.getText().toString();
    int equação = Integer.parseInt(myEditValue);
    editTextView.setText(equação + "CERTO!");} 

It gives error when there are characters of type "(" or "+" etc. Is there any way to recognize them?

    
asked by anonymous 20.07.2017 / 21:28

2 answers

2

Find this in the forum, and found it interesting! I do not know if it will work, but you do not have to try it!

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;    

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String infix = "3+2*(4+5)";
System.out.println(engine.eval(infix));

Hope it helps! : D

Solution link

    
20.07.2017 / 22:32
0

There are three simple ways to solve:

1) Add the attribute below in your EditText and avoid unwanted characters:

android:inputType="number"

2) Use the methods of the String class itself:

EditText editTextView = (EditText) findViewById(R.id.editTextView);
String myEditValue = editTextView.getText().toString();

//Removendo caracteres indesejados
myEditValue.replace("(", "");
myEditValue.replace("+", "");

int equação = Integer.parseInt(myEditValue);
editTextView.setText(equação + "CERTO!");

3) Search a little about Regex, which is a String used to validate other Strings, and if the user enters an unwanted character, display a message to it. There is the method of class String mEditValue.replaceAll(String regex, String substituta) , which with Regex prevents you from using step 2 for all cases.

Good Luck.

    
22.07.2017 / 04:22