Android 用空格检查输入

Android 用空格检查输入,android,Android,我制作了一个离线货币转换器,它使用TextWatcher获取用户在EditText部分的输入,并从方法返回所需的ouptut…我还制作了一种用户不能插入null的方式“编辑文本部分中的值,然后使用euro.getText按转换按钮!”==例如,null。但是当用户在输入之间留有一些空间时,我不知道如何继续,例如29 50。这将使我的程序崩溃。我的问题是,我应该使用什么来检查带有空间的输入,以避免程序崩溃?谢谢。您的程序崩溃时出现数字格式异常。你可以这样做: try{ double val

我制作了一个离线货币转换器,它使用TextWatcher获取用户在EditText部分的输入,并从方法返回所需的ouptut…我还制作了一种用户不能插入null的方式“编辑文本部分中的值,然后使用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.
}

您的程序因数字格式异常而崩溃。你可以这样做:

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 unspaced = edittext.getText().toString().replace(' ', '.'); // or ,  depending on what your app uses

这其实很容易。 你的应用程序接受带逗号或圆点的数字吗?无论哪种方式,您都可以使用以下符号将
字符串
替换为您选择的符号:

String unspaced = edittext.getText().toString().replace(' ', '.'); // or ,  depending on what your app uses

您的
parseDouble(…)
示例不正确
EditText.getText()
返回一个
可编辑的
而不是
字符串
。它应该是
Double.parseDouble(editText.getText().toString())
。这也适用于您的第二个示例(对于正则表达式)。当我尝试使用正则表达式“无效转义序列(有效的转义序列是\b\t\n\f\r\“\'\\”)”…我使用匹配(“\d+\.\d+”)。我认为应该是匹配(\\d+\.\\d+”)。是的,我在编辑editText.toString()时编辑了它。我也很抱歉。昨天我不得不用ruby编写一些正则表达式,我有点搞混了。你的
parseDouble(…)
示例不正确
EditText.getText()
返回一个
可编辑的
而不是
字符串
。它应该是
Double.parseDouble(editText.getText().toString())
。这也适用于您的第二个示例(对于正则表达式)。当我尝试使用正则表达式“无效转义序列(有效的转义序列是\b\t\n\f\r\“\'\\”)”…我使用匹配(“\d+\.\d+”)。我认为应该是匹配(\\d+\.\\d+”)。是的,我在编辑editText.toString()时编辑了它。我也很抱歉。昨天我不得不用ruby写一些正则表达式,我有点搞混了。