Java发票应用问题:无法正确计算发票金额与折扣平均值
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:
Check Variable Scope & Initialization
If you declared your total invoice amount and total discount variables inside your input loop (like inside thedoblock), 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;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!)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.Avoid Integer Division (Just in Case)
Even if your totals are correct, if you're usingintfor totals and dividing by anintcount, you might get integer division (e.g., 100 / 3 = 33 instead of 33.33). Usingdoublefor 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
totalInvoiceandtotalDiscountoutside the input loop? - Are you adding each invoice's values to these totals every time?
- Are you using
double(notint) 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

