当double为空时,Android应用程序崩溃

时间:2015-04-12 14:04:20

标签: android

我正在制作三角形计算器,但是当我将任何文本字段留空时,它会崩溃。 现在我想将num2添加到num4并在num1处获得答案,但是当我将num1留空时它会崩溃。 这是我的代码

public void onButtonClick(View v) {
    EditText a1 = (EditText) findViewById(R.id.TFnum1);
    EditText a2 = (EditText) findViewById(R.id.TFnum2);
    EditText a3 = (EditText) findViewById(R.id.TFnum4);

    TextView tv = (TextView) findViewById(R.id.TFnum7); //P
    TextView tv1 = (TextView) findViewById(R.id.TFnum6); //S
    TextView tv2 = (TextView) findViewById(R.id.TFnum1); //a
    boolean flag = false;
    double num1, num2, num4, ans;
    num1 = Double.parseDouble(a1.getText().toString());
    num2 = Double.parseDouble(a2.getText().toString());
    num4 = Double.parseDouble(a3.getText().toString());
    ans = 0;


    //a
    if (v.getId() == R.id.Badd) if (num2 == 0) {
        flag = true;
    } else ans = num2 + num4;
    tv2.setText(ans + "");


    //S
    if (v.getId() == R.id.Badd) if (num2 == 0) flag = true;
    else ans = num1 * num2 / 2;
    tv1.setText(ans + "");

    //P
    if (v.getId() == R.id.Badd) if (num2 == 0) flag = true;
    else ans = num1 + num2 + num4;
    tv.setText(ans + "");
}

2 个答案:

答案 0 :(得分:2)

嗨,欢迎来到StackOverflow。

您的错误是因为空指针异常,当您在空的edittext上调用getText时会抛出此错误。

基本上你正在尝试使用一个没有值的对象内存引用(a1),这不是Java的设计方式。如果要在RAM中放置引用,编译器需要在内存中有一些值。

确保您有适当的支票,例如

 if(a1.getText()!=null) { ...}

答案 1 :(得分:0)

试试这个:

    public void onButtonClick(View v) {
        EditText a1 = (EditText) findViewById(R.id.TFnum1);
        EditText a2 = (EditText) findViewById(R.id.TFnum2);
        EditText a3 = (EditText) findViewById(R.id.TFnum4);

        TextView tv = (TextView) findViewById(R.id.TFnum7); //P
        TextView tv1 = (TextView) findViewById(R.id.TFnum6); //S
        TextView tv2 = (TextView) findViewById(R.id.TFnum1); //a
        boolean flag = false;
        double num1, num2, num4, ans;
        num1 = ParseDouble(a1.getText().toString());
        num2 = ParseDouble(a2.getText().toString());
        num4 = ParseDouble(a3.getText().toString());
        ans = 0;


        //a
        if (v.getId() == R.id.Badd) if (num2 == 0) {
            flag = true;
        } else ans = num2 + num4;
        tv2.setText(ans + "");


        //S
        if (v.getId() == R.id.Badd) if (num2 == 0) flag = true;
        else ans = num1 * num2 / 2;
        tv1.setText(ans + "");

        //P
        if (v.getId() == R.id.Badd) if (num2 == 0) flag = true;
        else ans = num1 + num2 + num4;
        tv.setText(ans + "");
    }

private double ParseDouble(String number) {
   if (number!= null && number.length() > 0) {
       try {
          return Double.parseDouble(number);
       } catch(Exception e) {
          return -1;// Will return -1 in case of exception, you can change it with another value
       }
   } 

   return 0;
}