这是一个新手问题,但我对编程确实很陌生,而且我刚上 11 年级的编程类(class)一周多一点。我们使用 Java,并使用 Netbeans。
我现在正在做的是:
During a special sale at a store, a 10% discount is taken off of purchases over $10.00.
Create an application that prompts the user for the amount of purchases and then returns the discounted price, as well as the discount amount itself.
我的代码:
DecimalFormat x = new DecimalFormat ("$###.00");
double purchases, discount, finalPrice;
purchases = Double.parseDouble (purchaseInput.getText ());
if (purchases >= 10) {
discount = purchases * 0.10;
}
else {
discount = 0;
}
finalPrice = purchases - discount;
discountOutput.setText (discount);
finalPriceOutput.setText (finalPrice);
问题出在最后两行。我正在尝试将值设置为文本字段。它说它正在寻找 double ,但需要java.lang.String
。我尝试使用 double.toString () 将它们更改为字符串,但它表示无法取消引用 double 。我现在很困惑,请帮忙。
我确信修复并不是很复杂,但我已经将迄今为止学到的每个内容部分都看了两遍,但仍然找不到如何解决我的问题。
最佳答案
您已经有一个 DecimalFormat
来将 double 转换为字符串。所以试试这个:
DiscountOutput.setText(x.format(Discount));
FinalPriceOutput.setText(x.format(FinalPrice));
您也可以不使用 DecimalFormat
来完成此操作,但结果会略有不同,因为数字的格式不是“$###.00”:
DiscountOutput.setText(Discount.toString());
FinalPriceOutput.setText(FinalPrice.toString());
另外,作为一个建议,我认为当您使用“$#,##0.00
”时,货币数量看起来更好。这样一来,千位分隔符 (,) 和 1 美元的小数部分就会显示为 $0.51,而不是 $.51,这看起来很奇怪。这样做:
DecimalFormat x = new DecimalFormat ("$#,##0.00");
关于java - double 和 Java.lang.String -文本字段的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853703/