我的Android简单兴趣计算器一直在崩溃

时间:2013-09-12 14:15:21

标签: android calculator

公共类Simple_Interest扩展了Activity {

EditText p, r, t, e, si;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_interest);
    p = (EditText) findViewById(R.id.edtprinci);
    r = (EditText) findViewById(R.id.edtrate);
    p = (EditText) findViewById(R.id.edtyear);
    si = (EditText) findViewById(R.id.edtres);
    btn = (Button) findViewById(R.id.butint);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub
            double n1 = 0;
            double n2 = 0;
            double n3 = 0;
            double ans = 0;
            n1 = Double.parseDouble(p.getText().toString());
            n2 = Double.parseDouble(r.getText().toString());
            n1 = Double.parseDouble(t.getText().toString());
            ans = (n1 * n2 * n3) / 100;
            si.setText(Double.toString(ans));
        }

    });
}

}

每当我尝试在模拟器中运行程序时,我都会收到错误对话框,名为“遗憾的是应用程序已停止工作”....

需要帮助......

1 个答案:

答案 0 :(得分:1)

你犯了一个错误:

p = (EditText) findViewById(R.id.edtprinci);
r = (EditText) findViewById(R.id.edtrate);
p = (EditText) findViewById(R.id.edtyear);

你有2次p而没有

p = (EditText) findViewById(R.id.edtprinci);
r = (EditText) findViewById(R.id.edtrate);
t = (EditText) findViewById(R.id.edtyear);

应该更好,否则t永远不会被初始化

同样适用于

        n1 = Double.parseDouble(p.getText().toString());
        n2 = Double.parseDouble(r.getText().toString());
        n1 = Double.parseDouble(t.getText().toString());

您需要将最后一个更改为

        n3 = Double.parseDouble(t.getText().toString());

你的onclick应该是这样的:

    public void onClick(View v) {
        double n1 = 0;
        double n2 = 0;
        double n3 = 0;
        double ans = 0;

        if( !p.getText().toString().equals("") && !r.getText().toString().equals("") &&!t.getText().toString().equals("") )
        {
        n1 = Double.parseDouble(p.getText().toString());
        n2 = Double.parseDouble(r.getText().toString());
        n1 = Double.parseDouble(t.getText().toString());
        ans = (n1 * n2 * n3) / 100;
        si.setText(Double.toString(ans));
        }
        else{
        si.setText("Missing data");
        }
    }

甚至更好用try and catch;)

Ps:你初始化变量e但你从不使用它:)