There is a simple condition, we enter one number (in EditText), then the second, they are multiplied together, the result is displayed in Toast. But how to push a condition only for integers? To enter numbers with tenths or negatives, a window is displayed, saying that you must enter an integer.

int i = Integer.parseInt(tv.getText().toString()); int i1 = Integer.parseInt(tv1.getText().toString()); int res = i*i1; 
  • 2
    If you want to prevent the possibility of input - use the event listener in the input field, like here: stackoverflow.com/questions/11134144/ ... But then still filter the resulting value. You can also use the parsing of a fractional value from the input field, then simply convert it to an integer type. - DimXenon
  • Thank you, read) - Morozov

2 answers 2

It is necessary to register in XML:

 android:inputType="number" 
  • Super) thanks) - Morozov
  • In this keyboard there is a separator for decimals, like, respectively, and the fractional number can be entered. And there is a minus sign there too. - pavlofff
  • Anyway, only integers can be entered! - sgentstuff

Integer.parseInt () if you pass a string that has a fractional part it throws an Exception, namely

 java.lang.NumberFormatException: For input string: "" 

That is, you can proceed from this parsing in try

  try { int i = Integer.parseInt(tv.getText().toString()); int i1 = Integer.parseInt(tv1.getText().toString()); int res = i * i1; }catch(NumberFormatException exc) { //Тут что вам нужно, если число с точкой } 

Well, check whether the number is negative or not, I think no problem.

You can do this here, a simple processing example.

  String s = "-5"; int i = 0; try { i = Integer.parseInt(s.toString()); if(i < 0) throw new Exception("Дробное"); }catch(NumberFormatException exc) { //если число дробное } catch(Exception exc) { //если число отрицательное System.out.print(exc.getMessage()); } 
  • Thank you, but this is precisely the difficulty. Write the CORRECTLY test for i so that it is not negative and fractional. - Morozov
  • What is the difficulty you have? - DmitriyKhirniy
  • I wrote int i, I thought that only integers would be entered, but I can also enter negative numbers in the emulator (I don’t know how to correctly write them so that they cannot be entered. - Morozov
  • Handle the onChange event (or similar) for the input field. And if you find an input character of a point, comma or minus (or all but numbers) - just do not update the state of the input field. - DimXenon
  • So, for example: stackoverflow.com/questions/11134144/… - DimXenon