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

Java嵌套while循环未按预期运行,数组实现销售报表遇阻求助

Troubleshooting Your Sales Report Program (Arrays + Nested While Loops)

Hey there, let's break this down step by step to get you unstuck—it’s totally normal to hit a wall with nested loops and array data management in coursework, so don’t stress!

First, Let’s Structure Your Data with Arrays

Since you’re using arrays for this task, parallel arrays are the go-to approach for coursework (before you learn about classes/objects). Here’s how to map your required data to arrays:

  • String[] employeeNames: Stores each employee’s name
  • double[] ytdSales: Tracks corresponding year-to-date sales values
  • int[] transactionIds: Holds unique transaction IDs
  • String[] transactionTypes: Captures transaction categories (e.g., "Sale", "Refund")
  • double[] transactionAmounts: Records the dollar amount for each transaction

Note: If your assignment allows it, ArrayList would be more flexible for dynamic data, but if arrays are required, just initialize them with a sufficiently large fixed length (e.g., final int MAX_TRANSACTIONS = 50) to avoid overflow.

Fixing Your Nested While Loops

Most nested loop issues stem from: missing input cleanup, un-updated loop conditions, or logical gaps in termination rules. Below is a working example that aligns with your requirements, plus explanations of common pitfalls:

import java.util.Scanner;

public class SalesReportGenerator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Initialize arrays with a max transaction limit
        final int MAX_TRANSACTIONS = 50;
        String[] employeeNames = new String[MAX_TRANSACTIONS];
        double[] ytdSales = new double[MAX_TRANSACTIONS];
        int[] transactionIds = new int[MAX_TRANSACTIONS];
        String[] transactionTypes = new String[MAX_TRANSACTIONS];
        double[] transactionAmounts = new double[MAX_TRANSACTIONS];
        
        int transactionCount = 0;
        boolean keepAddingTransactions = true;
        
        // Outer loop: Controls whether to add another transaction
        while (keepAddingTransactions && transactionCount < MAX_TRANSACTIONS) {
            System.out.println("\n--- New Transaction #" + (transactionCount + 1) + " ---");
            
            // Input employee name
            System.out.print("Enter employee name: ");
            employeeNames[transactionCount] = scanner.nextLine();
            
            // Input valid YTD sales (inner loop ensures non-negative numbers)
            double validYtd = 0.0;
            boolean isYtdValid = false;
            while (!isYtdValid) {
                System.out.print("Enter year-to-date sales: ");
                if (scanner.hasNextDouble()) {
                    validYtd = scanner.nextDouble();
                    if (validYtd >= 0) {
                        isYtdValid = true;
                        ytdSales[transactionCount] = validYtd;
                    } else {
                        System.out.println("Error: YTD sales can't be negative. Try again.");
                    }
                } else {
                    System.out.println("Error: Please enter a valid number.");
                    scanner.next(); // Clear invalid input to avoid infinite loop
                }
            }
            scanner.nextLine(); // Clean up leftover newline character
            
            // Input unique transaction ID (inner loop checks for validity)
            int validTransId = 0;
            boolean isIdValid = false;
            while (!isIdValid) {
                System.out.print("Enter transaction ID: ");
                if (scanner.hasNextInt()) {
                    validTransId = scanner.nextInt();
                    if (validTransId > 0) {
                        // Optional: Check for duplicate IDs
                        boolean idExists = false;
                        for (int i = 0; i < transactionCount; i++) {
                            if (transactionIds[i] == validTransId) {
                                idExists = true;
                                break;
                            }
                        }
                        if (!idExists) {
                            isIdValid = true;
                            transactionIds[transactionCount] = validTransId;
                        } else {
                            System.out.println("Error: This ID is already in use. Try again.");
                        }
                    } else {
                        System.out.println("Error: Transaction ID must be positive.");
                    }
                } else {
                    System.out.println("Error: Please enter a valid integer.");
                    scanner.next(); // Clear invalid input
                }
            }
            scanner.nextLine(); // Clean up newline
            
            // Input valid transaction type (inner loop restricts to allowed values)
            String validType = "";
            boolean isTypeValid = false;
            while (!isTypeValid) {
                System.out.print("Enter transaction type (Sale/Refund): ");
                validType = scanner.nextLine().trim();
                if (validType.equalsIgnoreCase("Sale") || validType.equalsIgnoreCase("Refund")) {
                    isTypeValid = true;
                    transactionTypes[transactionCount] = validType;
                } else {
                    System.out.println("Error: Type must be 'Sale' or 'Refund'.");
                }
            }
            
            // Input valid transaction amount (inner loop aligns with transaction type)
            double validAmount = 0.0;
            boolean isAmountValid = false;
            while (!isAmountValid) {
                System.out.print("Enter transaction amount: ");
                if (scanner.hasNextDouble()) {
                    validAmount = scanner.nextDouble();
                    if ((validType.equalsIgnoreCase("Sale") && validAmount > 0) || 
                        (validType.equalsIgnoreCase("Refund") && validAmount < 0)) {
                        isAmountValid = true;
                        transactionAmounts[transactionCount] = validAmount;
                        // Update YTD sales with the new transaction
                        ytdSales[transactionCount] += validAmount;
                    } else {
                        System.out.println("Error: Sales need positive amounts, Refunds need negative amounts.");
                    }
                } else {
                    System.out.println("Error: Please enter a valid number.");
                    scanner.next(); // Clear invalid input
                }
            }
            scanner.nextLine(); // Clean up newline
            
            transactionCount++;
            
            // Ask user if they want to add another transaction
            System.out.print("Add another transaction? (Y/N): ");
            String userChoice = scanner.nextLine().trim();
            if (!userChoice.equalsIgnoreCase("Y")) {
                keepAddingTransactions = false;
            }
        }
        
        // Generate final sales report
        System.out.println("\n=== Final Sales Report ===");
        System.out.printf("%-20s %-15s %-10s %-10s %-15s\n", 
            "Employee", "YTD Sales", "Trans ID", "Type", "Amount");
        for (int i = 0; i < transactionCount; i++) {
            System.out.printf("%-20s $%-14.2f %-10d %-10s $%-14.2f\n", 
                employeeNames[i], ytdSales[i], transactionIds[i], transactionTypes[i], transactionAmounts[i]);
        }
        
        scanner.close();
    }
}

Key Pitfalls to Avoid

  • Scanner newline cleanup: After using nextInt()/nextDouble(), always call nextLine() to clear leftover newline characters—this prevents the next nextLine() from reading an empty string.
  • Loop condition updates: Make sure inner loop flags (like isYtdValid) are set to true only when valid input is received, otherwise you’ll hit infinite loops.
  • Array boundaries: Add a check like transactionCount < MAX_TRANSACTIONS to the outer loop to avoid ArrayIndexOutOfBoundsException.

If you’re hitting a specific error (e.g., infinite loops, skipped inputs) with your existing code, share a snippet and I can help debug it further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:37:11