我正在Android Studio中工作,必须创建一个应用程序,该应用程序允许用户输入他们已经吃过的一顿饭的价格,然后从保管箱中选择小费金额(5%,10%,15%, 20%和25%),然后可以单击一个按钮以获取他们用餐的最终总金额。除了计算总数之外,我几乎完成了所有工作。到目前为止,这是我的代码:
public class MainActivity extends AppCompatActivity {
double mealCost;
double totalCharges;
double tip;
String tipPercent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText mealAmount = (EditText)findViewById(R.id.txtMealAmount);
final Spinner group =(Spinner)findViewById(R.id.txtGroup);
Button charges = (Button)findViewById(R.id.btnCharge);
charges.setOnClickListener(new View.OnClickListener() {
final TextView result = ((TextView)findViewById(R.id.txtResult));
@Override
public void onClick(View view) {
String holdEditText = "";
holdEditText = mealAmount.getText().toString();
try {
mealCost = Double.parseDouble(holdEditText);
} catch (NumberFormatException d) {
mealCost = 0;
}
DecimalFormat currency = new DecimalFormat("$###,###.##");
tipPercent = group.getSelectedItem().toString();
try {
tip = Double.parseDouble(tipPercent);
} catch (NumberFormatException d) {
tip = 0;
}
totalCharges = mealCost + (mealCost + tip);
result.setText("Total cost of a meal that is $" + mealCost + " and a tip of "
+ tipPercent + " is " + currency.format(totalCharges));
}
});
}}
我遇到的问题在于以下代码行:
totalCharges = mealCost + (mealCost + tip);
当应用程序计算总数时,它总是使小费变为0,而不考虑用户从下拉框中选择了哪个小费百分比。我尝试取出“ tip = 0;”。代码部分,但最终会使应用程序完全忽略提示。我已经坚持了一段时间,不知道该怎么办。任何帮助将不胜感激。
答案 0 :(得分:0)
由于您的tipPercent
的类型为 5%,因此您可以尝试以下操作:
Double tip = new Double(tipPercent.trim().replace("%", ""))/100;
,tip的结果值为 0.05