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

如何重置构造函数的Getters和Setters?Java作业产品信息修改求助

Hey Nick, let's work through how to properly implement this task using getters/setters and meet your requirement of updating product information shared across classes. First, let's fix some obvious issues in your current code, then refactor the solution step by step.

问题分析与解决方案

1. 先修正代码中的拼写与逻辑错误

Your code has a few small but critical bugs that need fixing first:

  • 拼写错误: setDescripption → setDescription (extra 'p'); constructor parameter expiarayDate → expiaryDate (matches the member variable name); for consistency, I'd recommend renaming date fields to expiryDate (standard English spelling)
  • LocalDate comparison error: In verifyExpireProduct, comparing LocalDate objects with == checks reference equality, not value equality. Use equals() instead, and add null checks to avoid NPEs:
    public void verifyExpireProduct() {
        if(expireDate != null && expireDate.equals(expiaryDate)) {
            System.out.println("Product is expired");
        } else {
            System.out.println("Product is not expired");
        }
    }
    
  • LocalDate.of parameter order: In setExpireDate, LocalDate.of(day, month, year) is backwards—this method takes (year, month, dayOfMonth) as arguments. Fix it to avoid invalid dates:
    LocalDate date = LocalDate.of(year, month, day);
    

2. 正确使用Getters和Setters重构editProductInformation

Your current method hardcodes values directly into member variables, which breaks encapsulation and isn't flexible. Instead, use setter methods to modify values, and make the method support dynamic input (either via parameters or user input):

方案一:Dynamic update via method parameters (great for programmatic/batch changes)

public void editProductInformation(int newId, String newDescription, double newRecommendedPrice, int newUnit, double newWeight) {
    // Use setters instead of direct member access to follow encapsulation principles
    setID(newId);
    setDescription(newDescription);
    setRecommendedUnitPrice(newRecommendedPrice);
    setUnit(newUnit);
    setWeight(newWeight);
}

方案二:Interactive update via user input (for manual edits)

public void editProductInformation() {
    System.out.println("=== Editing Product Information ===");
    
    System.out.print("Enter new product ID: ");
    int newId = input.nextInt();
    input.nextLine(); // Clear the newline from the input buffer
    
    System.out.print("Enter new product description: ");
    String newDescription = input.nextLine();
    
    System.out.print("Enter new recommended unit price: ");
    double newPrice = input.nextDouble();
    
    System.out.print("Enter new unit count: ");
    int newUnit = input.nextInt();
    
    System.out.print("Enter new weight: ");
    double newWeight = input.nextDouble();
    
    // Use setters to apply changes
    setID(newId);
    setDescription(newDescription);
    setRecommendedUnitPrice(newPrice);
    setUnit(newUnit);
    setWeight(newWeight);
    
    System.out.println("Product information updated successfully!");
}

3. 实现"所有类共享产品主要信息"的需求

If your goal is to have all instances of the Product class share the same ID, description, etc., you'll need to mark these fields as static (so they belong to the class, not individual instances) and update your getters/setters to be static methods:

Step 1: Make shared fields static

protected static int ID;
protected static String description;
protected static double recommendedUnitPrice;
protected static int Unit = 1;
protected static double weight;

// Keep non-shared fields (like expiry dates) as non-static
protected LocalDate expiryDate;
protected LocalDate expireDate;

Step 2: Update getters/setters to static methods

public static int getID() { return ID; }
public static void setID(int newId) { ID = newId; }

public static String getDescription() { return description; }
public static void setDescription(String newDescription) { description = newDescription; }

// Repeat for other static fields

Step 3: Refactor the edit method for static fields

You can make the edit method static too, so you don't need an instance to call it:

public static void editSharedProductInformation(int newId, String newDescription, double newRecommendedPrice, int newUnit, double newWeight) {
    setID(newId);
    setDescription(newDescription);
    setRecommendedUnitPrice(newRecommendedPrice);
    setUnit(newUnit);
    setWeight(newWeight);
}

Now, any changes made via this method will be reflected across all Product instances, since they share the static fields.

4. Extra Optimization Tips

  • Add input validation to setters: Ensure data integrity by checking values before assigning them, e.g.:
    public void setID(int newId) {
        if (newId > 0) {
            this.ID = newId;
        } else {
            throw new IllegalArgumentException("Product ID must be a positive number");
        }
    }
    
  • Clean up Scanner resources: Since your Scanner is a member variable, call input.close() when you're done using it to avoid resource leaks.
  • Clarify date field names: Rename expiaryDate and expireDate to something more descriptive (like manufacturerExpiryDate and storeExpiryDate) to avoid confusion.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:13:58