簡體   English   中英

Android Eclipse EditText崩潰

[英]Android Eclipse EditText crash

我正在嘗試累積GPA應用程序。 它包含7個editTexts和一個textView 其中一項用於課程數量,其他用於課程GPA。 當我將其用作6門課程時,它可以工作,但是當我將其用作3門課程為例時,則必須讓其中3門為空,否則應用程序崩潰。

public class MainActivity extends Activity {

    EditText e1, e2, e3, e4, e5, e6, e7;
    TextView t1;
    Button b1, b2;
    double a=0;
    double b=0;
    double c=0;
    double d=0;
    double e=0;
    double f=0;
    double g=0;
    double h=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        e1=(EditText)findViewById(R.id.editText1);
        e2=(EditText)findViewById(R.id.editText2);
        e3=(EditText)findViewById(R.id.editText3);
        e4=(EditText)findViewById(R.id.editText4);
        e5=(EditText)findViewById(R.id.editText5);
        e6=(EditText)findViewById(R.id.editText6);
        e7=(EditText)findViewById(R.id.editText7);

        t1=(TextView)findViewById(R.id.textView3);
        b2=(Button)findViewById(R.id.button2);

        b2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            a=Double.parseDouble(e1.getText().toString());
            b=Double.parseDouble(e2.getText().toString());
            c=Double.parseDouble(e3.getText().toString());
            d=Double.parseDouble(e4.getText().toString());
            e=Double.parseDouble(e5.getText().toString());
            f=Double.parseDouble(e6.getText().toString());
            g=Double.parseDouble(e7.getText().toString());



            h= ((a+b+c+d+e+f)/g);


            t1.setText(Double.toString(h));

我嘗試了這段代碼:

{
    if (g==3)
    e4.setText("0");
    e5.setText("0");
    e6.setText("0");
}

但同樣的事情發生了。 注意:e7 =課程數

當您保持edittext的任何一個為空時,您的代碼將崩潰,例如:如果editext e1為空,則下面的代碼將無法正常工作,因為getText()。toString()沒有任何數據

a=Double.parseDouble(e1.getText().toString());

你必須喜歡

if(!e1.getText().toString().equals(""))
{
a=Double.parseDouble(e1.getText().toString());
}

至於所有.....

像這樣修改您的getText行:

String e1 = e1.getText().toString();
a= e1.equals("")?0:Double.parseDouble(e1);

這將防止您現在必須獲取NumberFormatException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM