我无法使用存储在所用变量上的值

时间:2019-03-27 01:01:16

标签: java android

我正试图从我所理解的值中获取用户的值输入,该用户称为花型,但该值存储在花型变量中,但是我无法将其用于计算。

public float spent, spentperson, totalspent, totaldivision,  debt;
public short people;

TextView debtoutput;
EditText spentinput;
Button Addbtn;

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

    debtoutput = findViewById(R.id.debtoutput);
    spentinput = findViewById(R.id.spentinput);
    Addbtn = findViewById(R.id.addbtn);

    Addbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            spent = Float.valueOf(spentinput.getText().toString());

            //showToast(String.valueOf(spent));
        }
    });


    showToast(String.valueOf(spent));

    people = 4;            //temporary
    spentperson = 5;        //temporary
    totalspent = spent + totalspent;
    totaldivision = totalspent / people;
    debt = totaldivision - spentperson;

    showToast(String.valueOf(debt));

    if (spent != 0) {
        if (debt < 0) {
            debtoutput.setText("You owe the following amount: " + debt);
        } else if (debt > 0) {
            debtoutput.setText("Someone is owing you: " + debt);
        } else {
            debtoutput.setText("There is no debt");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我还没有测试,但是乍看之下,您是从onClick内的EditText检索值的,因此,其余代码无法访问此值。

您也许可以将所有这些内容放入这样的方法中:

public void yourMethod(String spent){

  //convert spent
  double spentValue = Double.parseDouble(spent);

  people = 4;            //temporary
  spentperson = 5;        //temporary
  totalspent = spentValue + totalspent;
  totaldivision = totalspent / people;
  debt = totaldivision - spentperson;

  if (spentValue != 0) {
      if (debt < 0) {
          debtoutput.setText("You owe the following amount: " + debt);
      } else if (debt > 0) {
          debtoutput.setText("Someone is owing you: " + debt);
      } else {
          debtoutput.setText("There is no debt");
      }
  }
}

//And you call it in the onClick method like this:


  Addbtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          yourMethod(spentinput.getText().toString());
      }
  });



//I don't know your main goal with this code, although, you can use the same logic for other code snippets.

//Hope it can help you. Have a nice day!