You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Java入门:商店程序用户输入的异常处理方案咨询

Java Exception Handling for Your Store Program (Beginner-Friendly)

Hey there! I get that figuring out exception handling for different input scenarios can feel overwhelming when you're starting out—let's walk through each of your requirements step by step with simple, actionable code examples using try-catch blocks. All of these are tailored to work with your existing Scanner-based input flow.


1. Fixing Input Type Mismatch (e.g., Non-Integer for Stock)

The main issue here is InputMismatchException thrown by Scanner when you call nextInt() but the user enters a string. We'll wrap the input in a loop with try-catch, and clear the Scanner buffer after an error to avoid infinite loops.

Example Code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class StoreUtils {
    public static int getValidStockInput(Scanner scanner) {
        int stock = -1;
        boolean isValid = false;
        
        while (!isValid) {
            try {
                System.out.print("Enter product stock (integer): ");
                stock = scanner.nextInt();
                isValid = true; // Exit loop if input is valid
            } catch (InputMismatchException e) {
                System.out.println("❌ Error: Please enter a valid whole number for stock.");
                scanner.next(); // Clear the invalid input from buffer
            }
        }
        return stock;
    }
}

How to use it: Call this method instead of directly using scanner.nextInt() when collecting stock. If the user enters garbage, it'll keep prompting until they enter a valid integer, and won't crash your program.


2. Validating Customer ID Format (8 Digits + 1 Letter)

We'll use a regular expression to check the ID format, and throw/catch an IllegalArgumentException if it doesn't match. This keeps your validation logic clean and reusable.

Example Code:

import java.util.Scanner;

public class StoreUtils {
    private static final String CUSTOMER_ID_PATTERN = "^\\d{8}[A-Za-z]$"; // 8 digits + 1 letter
    
    public static String getValidCustomerId(Scanner scanner) {
        String customerId = "";
        boolean isValid = false;
        
        while (!isValid) {
            try {
                System.out.print("Enter customer ID (8 digits + 1 letter, e.g., 13234354A): ");
                customerId = scanner.nextLine().trim();
                
                if (!customerId.matches(CUSTOMER_ID_PATTERN)) {
                    // Throw custom exception if format is wrong
                    throw new IllegalArgumentException("Invalid ID format");
                }
                isValid = true;
            } catch (IllegalArgumentException e) {
                System.out.println("❌ Error: ID must be 8 digits followed by 1 letter (uppercase or lowercase).");
            }
        }
        return customerId;
    }
}

Regex Breakdown:

  • ^\\d{8}: Starts with exactly 8 digits
  • [A-Za-z]$: Ends with one uppercase or lowercase letter
  • The trim() ensures we ignore accidental spaces.

3. Handling Enum & Boolean Input Exceptions

Enum Input (e.g., Product Category)

When converting user input to an enum, IllegalArgumentException is thrown if the input doesn't match any enum constant. We'll catch this and prompt the user to enter a valid option.

Example Code:

import java.util.Scanner;

// First, define your enum
enum ProductCategory {
    ELECTRONICS, CLOTHING, FOOD, FURNITURE
}

public class StoreUtils {
    public static ProductCategory getValidProductCategory(Scanner scanner) {
        ProductCategory category = null;
        boolean isValid = false;
        
        while (!isValid) {
            try {
                System.out.print("Enter product category (ELECTRONICS/CLOTHING/FOOD/FURNITURE): ");
                String input = scanner.nextLine().trim().toUpperCase(); // Normalize input to uppercase
                category = ProductCategory.valueOf(input);
                isValid = true;
            } catch (IllegalArgumentException e) {
                System.out.println("❌ Error: Please enter one of the valid categories listed.");
            }
        }
        return category;
    }
}

Boolean Input (e.g., "Is this product on sale?")

Instead of forcing users to enter true/false, we can accept simpler inputs like Y/N and validate them. If they enter something else, we'll catch the invalid input (via a check) and prompt again.

Example Code:

import java.util.Scanner;

public class StoreUtils {
    public static boolean getValidBooleanInput(Scanner scanner, String prompt) {
        boolean result = false;
        boolean isValid = false;
        
        while (!isValid) {
            try {
                System.out.print(prompt + " (Y/N): ");
                String input = scanner.nextLine().trim().toUpperCase();
                
                if (input.equals("Y")) {
                    result = true;
                    isValid = true;
                } else if (input.equals("N")) {
                    result = false;
                    isValid = true;
                } else {
                    throw new IllegalArgumentException("Invalid boolean input");
                }
            } catch (IllegalArgumentException e) {
                System.out.println("❌ Error: Please enter 'Y' for Yes or 'N' for No.");
            }
        }
        return result;
    }
}

Usage: boolean isOnSale = getValidBooleanInput(scanner, "Is this product on sale?")


Putting It All Together

You can call these utility methods from your menu logic. For example, when creating a product:

public class ProductMenu {
    public static void createProduct(Scanner scanner) {
        System.out.println("\n=== Create New Product ===");
        System.out.print("Enter product name: ");
        String name = scanner.nextLine().trim();
        int stock = StoreUtils.getValidStockInput(scanner);
        scanner.nextLine(); // Clear leftover newline from nextInt()
        ProductCategory category = StoreUtils.getValidProductCategory(scanner);
        boolean isOnSale = StoreUtils.getValidBooleanInput(scanner, "Is this product on sale?");
        
        // Now create your Product object with these valid inputs
        Product newProduct = new Product(name, stock, category, isOnSale);
        // Add to inventory...
        System.out.println("✅ Product created successfully!");
    }
}

All of these examples use basic try-catch blocks, avoid complex libraries, and are designed to be easy to modify for your specific store program. No more crashes from bad user input!

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

火山引擎 最新活动