解析java.lang.NumberFormatException:无效的double:“”而不会丢失占位符文本

时间:2015-06-28 10:53:19

标签: java android string android-edittext

初始化Hello上的EditTexts返回一个“”,它无法转换为有效的double,因此会出现此错误。使用显式值可能会有所帮助,但之后我将丢失onCreate文本。
如何解决此问题而不会丢失android:hint文字?

android:hint

Code

public class MainActivity extends Activity { private double quant, problem, verbal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText quantScore = (EditText) findViewById(R.id.quant); EditText problemScore = (EditText) findViewById(R.id.problem); EditText verbalScore = (EditText) findViewById(R.id.verbal); Button calculate = (Button) findViewById(R.id.button); quant = Double.valueOf(quantScore.getText().toString()); problem = Double.valueOf(problemScore.getText().toString()); verbal = Double.valueOf(verbalScore.getText().toString()); final double total = quant + problem + verbal; calculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "The total is " +total, Toast.LENGTH_LONG).show(); } }); }

Layout

1 个答案:

答案 0 :(得分:1)

您应该捕获NumberFormatException并提供所需的默认值。

try {
   quant = Double.valueOf(quantScore.getText().toString());
} catch(NumberFormatException e) {
   quant = 0;
}

这不适用于EditText为空时无法解析为 Double 的任何文字。