You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java发票应用问题:无法正确计算发票金额与折扣平均值

Troubleshooting Your Invoice App's Average Calculations

Hey there! Welcome to Java programming—super stoked you're building your first app, and kudos on getting most of the functionality working already! 😊 Let's figure out why those averages are showing up as 0.0 when you enter "n".

Common Causes & Fixes

The 0.0 result almost always boils down to sum variables not being properly accumulated or scoped incorrectly. Here's what to check and fix:

  1. Check Variable Scope & Initialization
    If you declared your total invoice amount and total discount variables inside your input loop (like inside the do block), they get reset to 0 every time the loop runs. That means when you calculate averages at the end, the totals are still 0—hence 0.0 when divided by the invoice count.

    ✅ Fix: Declare these totals outside the loop, so they persist across iterations:

    int invoiceCount = 0;
    double totalInvoice = 0.0; // Lives outside the loop
    double totalDiscount = 0.0;
    
  2. Verify You're Actually Accumulating Totals
    After you calculate the current invoice's amount and discount, make sure you add them to your total variables. It's easy to forget this step!

    ✅ Example of the accumulation logic inside your loop:

    // After getting user input for invoice amount and discount percentage
    double currentDiscount = invoiceAmount * (discountPercent / 100.0);
    totalInvoice += invoiceAmount; // Add current invoice to total
    totalDiscount += currentDiscount; // Add current discount to total
    invoiceCount++; // Increment count (you said this works, but double-check!)
    
  3. Calculate Averages After the Loop Ends
    Make sure you're only computing the averages after the user has entered "n" and the loop exits. If you try calculating them inside the loop, you'll get partial values, but if you're seeing 0.0, this is less likely the issue.

  4. Avoid Integer Division (Just in Case)
    Even if your totals are correct, if you're using int for totals and dividing by an int count, you might get integer division (e.g., 100 / 3 = 33 instead of 33.33). Using double for totals fixes this, as shown in the code above.

Example Working Code Snippet

Here's a trimmed-down version of how your core logic should look to get the averages right:

import java.util.Scanner;

public class InvoiceApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int invoiceCount = 0;
        double totalInvoiceAmount = 0.0;
        double totalDiscountAmount = 0.0;
        String keepGoing;

        do {
            // Get user input
            System.out.print("Enter invoice amount: ");
            double amount = scanner.nextDouble();
            System.out.print("Enter discount % (e.g., 5 for 5%): ");
            double discountPercent = scanner.nextDouble();
            scanner.nextLine(); // Clear the newline from input buffer

            // Calculate and accumulate
            double discount = amount * (discountPercent / 100.0);
            totalInvoiceAmount += amount;
            totalDiscountAmount += discount;
            invoiceCount++;

            // Ask to continue
            System.out.print("Enter another invoice? (y/n): ");
            keepGoing = scanner.nextLine();
        } while (keepGoing.equalsIgnoreCase("y"));

        // Calculate and display averages (only if there are invoices)
        if (invoiceCount > 0) {
            double avgInvoice = totalInvoiceAmount / invoiceCount;
            double avgDiscount = totalDiscountAmount / invoiceCount;
            System.out.println("\n--- Invoice Summary ---");
            System.out.printf("Total invoices: %d%n", invoiceCount);
            System.out.printf("Average invoice amount: $%.2f%n", avgInvoice);
            System.out.printf("Average discount amount: $%.2f%n", avgDiscount);
        } else {
            System.out.println("No invoices were entered.");
        }

        scanner.close();
    }
}

Quick Checklist for Your Code

  • Did you declare totalInvoice and totalDiscount outside the input loop?
  • Are you adding each invoice's values to these totals every time?
  • Are you using double (not int) for the total variables to preserve decimal values?

Give these checks a go, and your averages should start showing up correctly. Let me know if you hit any snags with specific parts of your code!

内容的提问来源于stack exchange,提问作者Marsha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:10:58