1

我对java相当陌生,我必须创建这个我不知道从哪里开始的程序。有人可以帮我做什么以及如何编写代码来开始吗?

编写一个模拟收银机的程序。提示用户输入三件商品的价格。将它们加在一起以获得小计。确定小计的税 (6%)。找到销售小计加税的总金额。显示每个项目的价格、小计金额、税额和最终金额。

到目前为止,我有这个:

package register;
import java.util.Scanner;

public class Register {

    public static void main(String[] args) {

        Scanner price = new Scanner(System.in);

        System.out.print("Please enter a price for item uno $");
        double priceuno = price.nextDouble();

        System.out.print("Please enter a price for item dos $" );
        double pricedos = price.nextDouble();

        System.out.print("Please enter a price for item tres $");
        double pricetres = price.nextDouble();

        double total = ((priceuno) + (pricedos) + (pricetres));
        System.out.println("The subtotal is $" + total);

        double tax = .06;

        double totalwotax = (total * tax );
        System.out.println("The tax for the subtotal is $" + totalwotax);
        double totalandtax = (total + totalwotax);
        System.out.println("The total for your bill with tax is $" + totalandtax);

    }
}

输出(假设价格为 price1 = 1.65、price2 = 2.82 和 price3 = $9.08)如下所示:

请为第 1 件商品定价 1.65 美元

请输入第二个商品的价格 $2.82

请输入第 3 件商品的价格 $9.08

小计为 13.55 美元

小计的税金为 0.81300000000000001 美元

您的税单总额为 14.363000000000001 美元

如何使小计和总账单的税款四舍五入到小数点后两位?

谢谢

4

4 回答 4

6

Java 有一个 DecimalFormat 类来处理这样的事情。

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

所以你想添加到你的代码中

 DecimalFormat df = new DecimalFormat("###,##0.00");

并将您的输出更改为

 double totalwotax = (total * tax );
 System.out.println("The tax for the subtotal is $" + df.format(totalwotax));
 double totalandtax = (total + totalwotax);
 System.out.println("The total for your bill with tax is $" + df.format(totalandtax));

这将确保您的美分的小数点右侧恰好有两位数,并在左侧至少保留一位,以防总金额低于 1 美元。如果其 1,000 或更高,它将在正确的位置用逗号格式化。如果您的总数高于 100 万,您可能必须将其更改为类似这样才能获得额外的命令

DecimalFormat df = new DecimalFormat("###,###,##0.00");

编辑: 所以 Java 还内置了对格式化货币的支持。忘记 DecimalFormatter 并使用以下内容:

NumberFormat nf = NumberFormat.getCurrencyInstance();

然后像使用 DecimalFormatter 一样使用它,但没有前面的美元符号(它将由格式化程序添加)

System.out.println("The total for your bill with tax is " + nf.format(totalandtax));

此外,此方法对区域设置敏感,因此如果您在美国,它将使用美元,如果在日本,则使用日元,依此类推。

于 2013-05-22T20:27:27.257 回答
5

永远不要double 为钱而使用,用户BigDecimal

于 2013-05-22T20:23:20.997 回答
2

你可以简单地试试这个

DecimalFormat df=new DecimalFormat("#.##");

税收

double totalwotax = 0.8130000000000001;
System.out.println("The tax for the subtotal is $" + df.format(totalwotax));

输出:0.81

总计

double totalandtax = 14.363000000000001;
System.out.println("The total for your bill with tax is $" + df.format(totalandtax));

输出:14.36

于 2013-10-17T06:39:24.117 回答
1

您可以使用该format()方法代替println()

System.out.format("The subtotal is $%.2f%n",  total);  

可以在此处找到格式语法的说明。

于 2013-05-22T20:23:09.163 回答