我正在制作一个简单的货币计算器用于学习目的,我不知道为什么我的代码不会起作用。目前,当我按下"转换"按钮有一条消息说" Appname停止工作"
以下是代码:
public class MainActivity extends AppCompatActivity {
//Button convertButton;
public void convert(View view) {
EditText dkk = (EditText) findViewById(R.id.dkkField);
EditText gbp = (EditText) findViewById(R.id.gbpField);
EditText eur = (EditText) findViewById(R.id.eurField);
EditText usd = (EditText) findViewById(R.id.usdField);
Double dkkNum = Double.parseDouble(dkk.getText().toString());
Double gbpNum = Double.parseDouble(gbp.getText().toString());
Double eurNum = Double.parseDouble(eur.getText().toString());
Double usdNum = Double.parseDouble(usd.getText().toString());
TextView textView = (TextView) findViewById(R.id.resultView);
double dkkTogbp;
double dkkToeur;
double dkkTousd;
double gbpToDkk;
double eurToDkk;
double usdToDkk;
if(dkk!=null){
dkkTogbp = dkkNum * 0.114001;
dkkToeur = dkkNum * 0.134489;
dkkTousd = dkkNum * 0.142729;
textView.setText(dkk+ "DKK is "+ dkkTogbp+" GBP, "+dkkToeur+"EUR, "+ dkkTousd +"USD");
}else if(gbp!=null){
gbpToDkk = gbpNum * 8.77189;
textView.setText(dkk+ "GBP is "+ gbpToDkk+" DKK");
}else if(eur!=null){
eurToDkk = eurNum * 7.43555;
textView.setText(dkk+ "EUR is "+ eurToDkk+" DKK");
}else if(usd!=null){
usdToDkk = usdNum * 7.00630;
textView.setText(dkk+ "USD is "+ usdToDkk+" DKK");
Toast.makeText(getApplicationContext(), dkk.toString() + " DKK", Toast.LENGTH_LONG).show();
}
dkk.setText("");
gbp.setText("");
eur.setText("");
usd.setText("");
}
我发现当我删除下面的代码块和if语句时程序可以运行而不会崩溃:
Double dkkNum = Double.parseDouble(dkk.getText().toString());
Double gbpNum = Double.parseDouble(gbp.getText().toString());
Double eurNum = Double.parseDouble(eur.getText().toString());
Double usdNum = Double.parseDouble(usd.getText().toString());
有人可以解释为什么会这样吗?
我没有收到任何错误。
答案 0 :(得分:1)
问题在于将文本解析为double值。
首先,您应该使用try-catch块来保存应用程序崩溃,如下所示:
try
{
Double dkkNum = Double.parseDouble(dkk.getText().toString());
Double gbpNum = Double.parseDouble(gbp.getText().toString());
Double eurNum = Double.parseDouble(eur.getText().toString());
Double usdNum = Double.parseDouble(usd.getText().toString());
}
catch(NumberFormatException ex)
{
// If the format of the input string is wrong, then you get here the error message
}
catch(NullPointerException ex)
{
// If the input string is null, then you get here the error message
}
检查应该解析的文本是否具有正确的语法,如“1.9”。
更新: 如果输入字符串为null,则“parseDouble”方法抛出“NullPointerException”。有关更多信息,请参阅this link。我已经更新了代码。