0

I want from user to enter the amount of money and I want to reject the input if it contains any letters or symbols etc.In other words I want it to contain only numbers.One solution I ve come up with is the following.

final EditText numberField = (EditText) findViewById(R.id.Cost);
 if(numberField != null) {
             test = numberField.getText().toString();
        }
        if(test.isEmpty()) {
                 Toast.makeText(this, "Tutar alanını doldurunuz", Toast.LENGTH_SHORT).show();         

        }else if(test.contains("a")||test.contains("b")
        } else {
                cost = Integer.parseInt(test.trim());
        }

I think this works but writing everything from test.contains("a") to test.contains("z") and the symbols is too long and makes the code look really bad. How can I accomplish my goal?

  • If this is android, you can set something (I forgot what though) on the EditText to only allow numbers. – Sweeper Jul 03 '16 at 00:03
  • Yes it is android and that information is helpful I will check that now. – Felipe Hield Jul 03 '16 at 00:05
  • You can use the XML attribute `inputType` or the method `setInputType`. If you use the XML attribute, set it to `number`. You can pass `InputType.TYPE_CLASS_NUMBER` to the method. – Sweeper Jul 03 '16 at 00:14

1 Answers1

1

If you don't want to add any extra libraries, you could just define an extra method as follows:

public boolean isDecimal(String str) {
    try {
        Double.parseDouble(str);
    }
    catch(NumberFormatException ex) {
        return false;
    }
    return true;
}

Of course, this will allow decimals (which I assume you want as we're talking about money) - if you just want whole numbers, use Integer.parseInt() instead.

Then your else if line becomes:

else if(isDecimal(test))
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 1
    I will accept this as an answer. My problem was on android so making edit text accept numbers only will be enough but this is a huge help for my other projects. – Felipe Hield Jul 03 '16 at 00:08