[英]Checking for input with space
我已经制作了一个脱机货币转换器,可以使用TextWatcher在EditText部分中输入用户的信息,并从方法中返回所需的输出...并且我已经实现了一种用户无法在其中插入“空”值的方式。例如EditEdit部分,然后使用euro.getText!== null按下转换按钮。但是当用户在输入之间留出一些空格(例如29 50)时,我不知道如何继续。我的问题是我应该使用什么来检查是否有空格输入以避免程序崩溃?谢谢。
您的程序因数字格式异常而崩溃。 您可以这样做:
try{
double value = Double.parseDouble(editText.getText().toString());
} catch(NumberFormatException ex){
Log.e(TAG, "improper number format");
//show some dialog saying what's the format that should be entered
}
您还可以使用正则表达式:
String editTextValue = editText.getText().toString();
if(editTextValue.matches("\\d+\\.\\d+")){
double value = Double.parseDouble(editTextValue);
} else{
//show dialog saying what should be the format.
}
这实际上很容易。 您的应用是否接受带逗号或点的数字? 无论哪种方式,您都可以使用以下命令将String
替换为您选择的符号:
String unspaced = edittext.getText().toString().replace(' ', '.'); // or , depending on what your app uses
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.