我正在尝试制作一个可以在人与人之间分配账单的应用程序,但是每当我尝试在代码中将两个数字相除时,它始终会给我0.0。为什么是这样?

这是代码:

public class MainActivity extends Activity {
    public int x = 0;
    public double y = 1.00;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Button
        Button btn = (Button) findViewById(R.id.button);

        //EditText
        EditText nop = (EditText) findViewById(R.id.editText);
        EditText cob = (EditText) findViewById(R.id.editText2);


        try{
            x = Integer.valueOf(nop.getText().toString());
        } catch (NumberFormatException e) {
            x = 0;
        }

        try{
            y = Double.valueOf(cob.getText().toString());
        } catch (NumberFormatException e) {
            y = 1.00;
        }


        //TextView
        final TextView tv = (TextView) findViewById(R.id.textView);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                 Double z = (y / x);
                tv.setText("You will each pay:" + (z));
            }
        });

    }
    }

最佳答案

单击按钮即可从EditText中获取值,否则您将无法获得输入的值,因为获取xy值的代码将在启动应用程序后立即执行,并且不再进行进一步的获取。

做这个

    final TextView tv = (TextView) findViewById(R.id.textView);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                x = Integer.valueOf(nop.getText().toString());
            } catch (NumberFormatException e) {
                x = 0;
            }

            try{
                y = Double.valueOf(cob.getText().toString());
            } catch (NumberFormatException e) {
                y = 1.00;
            }

             Double z = (y / x);
            tv.setText("You will each pay:" + (z));
        }
    });

10-08 01:44