我的学校作业遇到了问题,我们必须为一家快餐公司创建一个PoS。部分工作是在输入招标金额后计算变更。我遇到的问题是程序无法从由于“ $”而支付的总额中减去总计。我的代码当前如下所示:
private void totalButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Finding the subtotal
double burgers;
double fries;
double drinks;
double subtotal;
burgers = 2.49;
fries = 1.89;
drinks = 0.99;
subtotal = Double.parseDouble (burgerInput.getText ()) * burgers
+ Double.parseDouble (fryInput.getText ()) * fries
+ Double.parseDouble (drinkInput.getText ()) * drinks;
DecimalFormat w = new DecimalFormat("###,###0.00");
subtotalOutput.setText("$" + w.format(subtotal));
// Calculating Tax
double taxpercentage;
double tax;
taxpercentage = 0.13;
tax = subtotal * taxpercentage;
DecimalFormat x = new DecimalFormat("###,###0.00");
taxesOutput.setText("$" + x.format(tax));
// Grand Total
double grandtotal;
grandtotal = subtotal + tax;
DecimalFormat y = new DecimalFormat("###,###0.00");
grandtotalOutput.setText("$" + y.format(grandtotal));
为了计算变化:
// Calculating Change
double tendered;
double grandtotal;
double change;
tendered = Double.parseDouble(tenderedInput.getText ());
grandtotal = Double.parseDouble(grandtotalOutput.getText ());
change = tendered - grandtotal;
DecimalFormat z = new DecimalFormat("###,###0.00");
changeOutput.setText("$" + z.format(change));
任何帮助忽略'$'符号以允许我将'$'保留在grandtotalOutput框中但仍能够正确计算更改的帮助将不胜感激。谢谢!
该$
顿号,需要从以文本去除它被解析成double
数。你可以通过链接来实现String#replace
,首先,
用空白文本替换,然后$
用空白文本替换。
tendered = Double.parseDouble(tenderedInput.getText().replace(",", "").replace("$", ""));
grandtotal = Double.parseDouble(grandtotalOutput.getText().replace(",", "").replace("$", ""));
注意:替换可以以任何顺序进行(即,首先替换$
为空白文本,然后,
替换为空白文本)。
起作用了,谢谢-必须在程序中包含$,因此我必须找到一种方法将其保存在其中(不幸的是,我们的老师提供的课程没有超过.replace()。
即使您的老师没有做任何事情,也最好阅读有关正在学习的课程的JavaDocs(课程的官方文档)。例如,有关String的文档将告诉您许多有趣的有用方法。