我使用 eclipse 和 android sdk (java) 创建了一个简单的程序,在 EditText box 中有一些限制,但是
当 EditText box 是空的时候程序就奔溃了。我用了很多方法来检查 EditText 是否为空,但是它还是不能
运行的。为什么当box是空的时候程序奔溃?
buttonHash.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
switch(v.getId()){
case R.id.hash_button:
TextView msg = (TextView)findViewById(R.id.tell);
info = (EditText)findViewById(R.id.entry);
anss = info.getText().toString();
//String ans = Double.toString(res);
double result = Double.parseDouble(anss);
if (res == result){
msg.setText("Correct");
}else
if (res != result){
msg.setText("Incorrect");
}else
if (info.getText().toString().equals("")){
msg.setText("Empty!");
}
}
}
});
使用下面的代码来解决你的问题
public void onClick(View v) {
if (_text.getText().toString().equals(""))
Toast.makeText(getApplicationContext(), "Empty BOX", 5000).show();
else
Toast.makeText(getApplicationContext(), _text.getText().toString(), 5000).show();
}
double result = Double.parseDouble(anss);
如果anss为空,那肯定会报错了
把
if (info.getText().toString().equals("")){
msg.setText("Empty!");
return;
}
放到double result = Double.parseDouble(anss);
前面
double result = Double.parseDouble(anss);
如果anss为空,那肯定会报错了,还有就是当你输入的是文字的话根本无法强转,所以程序肯定会崩溃
应该是这句代码Double.parseDouble(anss);报的空指针异常