我是Android Studio的新手,Java对我来说很新。我正在尝试制作一个转换应用程序。 为此,我必须获取编辑文本框的值并将其转换为数字。那是我的应用程序崩溃的时候,我添加的那一刻:
double n1Var = Double.parseDouble(n1.getText().toString());
我的应用将打开,然后立即关闭。如果我删除它,该应用程序可以正常工作。我尝试了不同的方法将其变成双精度,尝试将其转换为整数仍然不起作用。如果我尝试一个字符串,它可以正常工作。
//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);
}
希望这有帮助。干杯和快乐编码。
没有任何效果.这是我的代码+当我按下按钮打开双精度的活动时的日志......
日志屏幕截图
EditText ETInput;
Button BConvert;
TextView TVresult;
RadioButton c2f;
RadioButton c2k;
RadioButton f2c;
RadioButton f2k;
RadioButton k2c;
RadioButton k2f;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
ETInput = (EditText)findViewById(R.id.ETInput);
double a = Double.parseDouble(ETInput.getText().toString());
BConvert = (Button)findViewById(R.id.BConvert);
TVresult = (TextView)findViewById(R.id.TVresult);
c2f = (RadioButton)findViewById(R.id.c2f);
c2k = (RadioButton)findViewById(R.id.c2k);
f2c = (RadioButton)findViewById(R.id.f2c);
f2k = (RadioButton)findViewById(R.id.f2k);
k2c = (RadioButton)findViewById(R.id.k2c);
k2f = (RadioButton)findViewById(R.id.k2f);
String val = ETInput.getText().toString().trim();
double var;
var = Double.parseDouble(val);
}
}
with this:
双W;
try {
w = new Double(input.getText().toString());
} catch (NumberFormatException e) {
w = 0;
}
w 始终为零
从 Java 文档中,以下是可以从Double.parseDouble
抛出的异常:
抛出:
空指针异常 - 如果字符串为空
NumberFormatException - 如果字符串不包含可解析的双精度。
从你的描述来看,很可能NullPointerException
被扔了。检查日志猫以准确找出抛出的异常。