@Override
public void onClick(View v)
{
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
}
上面是我的代码,当我将其中任何一个留空时,它会崩溃。如何克服它。
只需检查用户是否输入了任何内容,然后解析您的值:
if(!Total.getText().toString().matches(""))
float num1 = Float.parseFloat(Total.getText().toString());
尝试使用 try...抓住
float num1 = 0.00f;
float num2 = 0.00f;
try {
num1 = Float.parseFloat(Total.getText().toString());
num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
catch(NumberFormatException ex) {
//Handle Non Float Exception
Toast.makeText(getApplicationContext(), "Invalid input !",Toast.LENGTH_LONG).show();
}
试试这个
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!Total.getText().toString().trim().equals("")&&!Done.getText().toString().trim().equals("")){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});
如果 EditText 不为空,则可以应用条件,则代码将像这样运行
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
String total=Total.getText().toString();
String done=Done.getText().toString();
if (!total.isEmpty() && !done.isEmpty()) {
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}else {
Toast.makeText(OpenFile.this, "Fill values", Toast.LENGTH_SHORT).show();
}
首先检查你是否正确找到编辑文本之后还要检查 isEmpty 条件以避免空指针异常
if (!editText1.getText().toString().isEmpty() && !editText2.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
}
检查空文本,如果不是空,则执行计算
if(!Total.getText().toString().isEmpty() && !Done.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});