Java发票总计和平均值

时间:2018-03-19 05:14:45

标签: java

我是新手,很高兴见到你!我在大学的Java 1课程,我们有这个发票申请。我已经编写了代码,除了给我平均发票金额和平均折扣金额外,我可以做任何事情。这应该显示用户是否输入“n”。

我可以做到这一切,包括获取发票总数,但我得到0.0作为我的平均折扣和平均发票金额的输出。我附上了代码,希望你能引导我朝着正确的方向前进。我要继续努力了。我希望今天能向你学习一些东西! :)

import java.util.Scanner;
public class InvoiceApp {

    public static void main(String[] args) {
        // welcome the user to the program
        System.out.println("Welcome to the Invoice Total Calculator");
        System.out.println();  // print a blank line

        //initialize variables
        int numberOfInvoices = 0;
        double totalDiscount = 0;
        double totalInvoice = 0;

        // create a Scanner object named sc
        Scanner sc = new Scanner(System.in);

        // perform invoice calculations only if "n" or "N" is entered
        String choice = "y";
                while (!choice.equalsIgnoreCase("n"))
        {
            // get the invoice subtotal from the user
            System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // calculate the discount amount and total
            double discountPercent;
            if (subtotal >= 500) {
                discountPercent = .25;
            } else if (subtotal >= 200) {
                discountPercent = .2;
            } else if (subtotal >= 100) {
                discountPercent = .1;
            } else {
                discountPercent = 0.0;
            }
            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // display the discount amount and total
            String message = "Discount percent: " + discountPercent + "\n"
                           + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";            
            System.out.println(message);

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();

            numberOfInvoices ++;

        //displays the invoice numbers, average invoice amount, and average
        //discount
    {
        double averageInvoiceAmount = totalInvoice/numberOfInvoices;
        double averageDiscount = totalDiscount/numberOfInvoices;
        String message2 = "\n"
                        + "Number of Invoices: " + numberOfInvoices + "\n"
                        + "Average Invoice Amount: " + averageInvoiceAmount + "\n"
                        + "Average Discount: " + averageDiscount + "\n";
        System.out.println(message2);
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

您尚未为“totalInvoice”和“totalDiscount”分配任何值。 这些变量设置为默认值,即0.0,因此您获得的输出为“平均折扣”和“平均发票金额”为0.0。

在代码中更新两者的值,然后您将获得正确的输出。