我正在開發移動應用程序開發課程,其中一個項目是小費計算器。我試圖將書中的代碼(使用滑塊)調整爲帶有四個按鈕的代碼。基本Android小費計算器
此代碼編譯並運行正常,但是當我點擊按鈕(15%,18%,20%和22%)時,它似乎無法運行計算 - 小費和總金額顯示最多爲0.00,每個人(如果你分割賬單,每個人都支付了什麼)顯示爲NaN(不是數字)。代碼很簡單,所以這可能是一個簡單的錯誤......但我不知道在哪裏這是,老師也沒有。我的代碼如下。
public class MainActivity extends Activity {
private static final NumberFormat currencyFormat =
NumberFormat.getCurrencyInstance();
private static final NumberFormat percentFormat =
NumberFormat.getPercentInstance();
private double billAmount = 0.0;
private double diners;
private double tipPercent;
private double tipAmount;
private double totalAmount;
private double eachPerson;
private TextView billTV;
private TextView tipTV;
private TextView totalTV;
private TextView eachTV;
private TextView dinersTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b15= (Button) findViewById(R.id.fifteenButton);
Button b18= (Button) findViewById(R.id.eighteenButton);
Button b20= (Button) findViewById(R.id.twentyButton);
Button b22= (Button) findViewById(R.id.twentytwobutton);
b15.setOnClickListener(buttonListener);
b18.setOnClickListener(buttonListener);
b20.setOnClickListener(buttonListener);
b22.setOnClickListener(buttonListener);
billTV = (TextView) findViewById(R.id.billAmount);
tipTV = (TextView) findViewById(R.id.tipAmount);
totalTV = (TextView) findViewById(R.id.totalAmount);
eachTV = (TextView) findViewById(R.id.eachPays);
dinersTV = (TextView) findViewById(R.id.diners);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public OnClickListener buttonListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.fifteenButton :
tipPercent = .15;
break;
case R.id.eighteenButton :
tipPercent = .18;
break;
case R.id.twentyButton :
tipPercent = .20;
break;
case R.id.twentytwobutton :
tipPercent = .22;
break;
}
tipAmount = (billAmount * tipPercent);
totalAmount = billAmount + tipAmount;
eachPerson = totalAmount/diners;
tipTV.setText(currencyFormat.format(tipAmount));
totalTV.setText(currencyFormat.format(totalAmount));
eachTV.setText(currencyFormat.format(eachPerson));
}
};
}
謝謝;修復它。 –
@KurtW請將答案標記爲正確,以便讓其他人從中受益 –