Android应用程序在试图从编辑文本中获取值并变成双精度文本时崩溃
我是android studio的新手,java对我来说是相当陌生的。我正在尝试制作一个转换应用程序。为此,我必须获得编辑文本框的值,并将其转换为数字。当我的应用程序崩溃时,我添加:Android应用程序在试图从编辑文本中获取值并变成双精度文本时崩溃,android,Android,我是android studio的新手,java对我来说是相当陌生的。我正在尝试制作一个转换应用程序。为此,我必须获得编辑文本框的值,并将其转换为数字。当我的应用程序崩溃时,我添加: double n1Var = Double.parseDouble(n1.getText().toString()); 我的应用程序打开,然后立即关闭。如果我删除它的应用程序工作良好。我试着用不同的方法把它变成一个双精度的,甚至试着把它变成一个整数仍然不起作用。如果我尝试一个字符串,它可以正常工作。来自Java,
double n1Var = Double.parseDouble(n1.getText().toString());
我的应用程序打开,然后立即关闭。如果我删除它的应用程序工作良好。我试着用不同的方法把它变成一个双精度的,甚至试着把它变成一个整数仍然不起作用。如果我尝试一个字符串,它可以正常工作。来自Java,下面是可以从Double.parseDouble
引发的异常:
抛出:
NullPointerException-如果字符串为null
NumberFormatException-如果字符串不包含可解析双精度
根据您的描述,很可能引发了NullPointerException
。检查以确定引发了哪个异常
//assuming that (EditText)n1 = (EditText)findViewById(R.id.id_of_n1);
String et_val = n1.getText().toString().trim();
double n1Var;
if(et_val.equals("") || et_val.length==0 ){
/*you can improve on this filter with a regex to check if the content of the edit text is event a number.
Furthermore, you can also control the entry of the information allowed into edit text with a switch in the xml for the edit text by allowing for only entry of numbers.
You can also do control the entry into the edit text with a java code that would compel the user to only enter numbers if that complies with what you are looking forward to executing with the user.
*/
n1Var = 0;
}else{
n1Var = Double.parseDouble(et_val);
}
//希望这有帮助。干杯和快乐的编码。似乎什么都不起作用。这是我的代码+当我按下按钮打开活动时的日志,其中有双人间 }有了这个: 双w
try {
w = new Double(input.getText().toString());
} catch (NumberFormatException e) {
w = 0;
}
w始终为零如果用户输入数字以外的任何内容或文本为空,应用程序将崩溃。在你的情况下,文本可能是空的。你的错误是什么?@Marusia Petrova,请发布你坠机的日志
try {
w = new Double(input.getText().toString());
} catch (NumberFormatException e) {
w = 0;
}