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

Eclipse提示‘The constructor Email() is undefined’问题排查及Java邮件管理应用封装扩展开发求助

Let's break down your problem step by step, fix the constructor error, and polish the code to meet your encapsulation and user-input goals.


1. Fixing the "The constructor Email() is undefined" Error

First off, your Email class does have a no-arg constructor defined—but there are two likely culprits for the error:

  • You might have modified the constructor recently but haven't re-compiled your Eclipse project. Try running Project > Clean... to force a re-build.
  • Your original no-arg constructor had broken logic: this.firstName = firstName; refers to the uninitialized class member variable (which is null), so it's effectively a no-op. This might have caused silent compilation issues that confused Eclipse.

Let's fix that constructor logic and build out the functionality you want.


2. Implementing User-Defined Names & Proper Encapsulation

Your goal is to let users input their own names instead of using hardcoded values. We'll adjust the code to support this, while tightening up encapsulation (proper getter/setter pairs, data consistency, and clean resource management).

Corrected Main Class

This version prompts the user for their first and last name, then passes those values to the Email constructor:

package encap;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Get user input for name
        System.out.print("Enter your first name: ");
        String firstName = scanner.nextLine();
        System.out.print("Enter your last name: ");
        String lastName = scanner.nextLine();
        
        // Create Email instance with user-provided names
        Email userEmail = new Email(firstName, lastName);
        System.out.println("\nYour account details:");
        System.out.println(userEmail.showInfo());
        
        scanner.close();
    }
}

Corrected Email Class

This version fixes the constructor logic, adds proper encapsulation, and ensures data consistency (like regenerating the email address if the user updates their name):

package encap;
import java.util.Scanner;

public class Email {
    // Private fields (encapsulated)
    private String firstName;
    private String lastName;
    private String password;
    private String department;
    private String email;
    private int mailboxCapacity = 500;
    private String alternateEmail;
    private final int DEFAULT_PASSWORD_LENGTH = 10; // Mark constants as final
    private final String COMPANY_SUFFIX = "company.com";

    // Primary constructor: accepts first/last name from user input
    public Email(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.department = selectDepartment();
        this.password = generateRandomPassword(DEFAULT_PASSWORD_LENGTH);
        this.email = buildEmailAddress();
        System.out.println("Your temporary password: " + this.password);
    }

    // Optional no-arg constructor: prompts user for names directly
    public Email() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first name: ");
        this.firstName = scanner.nextLine();
        System.out.print("Enter last name: ");
        this.lastName = scanner.nextLine();
        
        this.department = selectDepartment();
        this.password = generateRandomPassword(DEFAULT_PASSWORD_LENGTH);
        this.email = buildEmailAddress();
        System.out.println("Your temporary password: " + this.password);
        
        scanner.close();
    }

    // Prompt user for department selection
    private String selectDepartment() {
        System.out.printf("New worker: %s %s%nDEPARTMENT CODES:%n1 for Sales%n2 for Development%n3 for Accounting%n0 for none%nEnter department code: ",
                firstName, lastName);
        
        Scanner in = new Scanner(System.in);
        int depChoice = in.nextInt();
        in.nextLine(); // Consume leftover newline character
        
        String dept;
        switch(depChoice) {
            case 1: dept = "Sales"; break;
            case 2: dept = "Development"; break;
            case 3: dept = "Accounting"; break;
            default: dept = "";
        }
        
        in.close();
        return dept;
    }

    // Generate a secure random password
    private String generateRandomPassword(int length) {
        String passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()";
        StringBuilder password = new StringBuilder(length);
        for(int i=0; i<length; i++) {
            int randIndex = (int) (Math.random() * passwordChars.length());
            password.append(passwordChars.charAt(randIndex));
        }
        return password.toString();
    }

    // Build the email address from component parts
    private String buildEmailAddress() {
        StringBuilder emailBuilder = new StringBuilder();
        emailBuilder.append(firstName.toLowerCase())
                   .append(".")
                   .append(lastName.toLowerCase())
                   .append("@");
        if(!department.isEmpty()) {
            emailBuilder.append(department.toLowerCase())
                       .append(".");
        }
        emailBuilder.append(COMPANY_SUFFIX.toLowerCase());
        return emailBuilder.toString();
    }

    // Getters and Setters (proper encapsulation)
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
        this.email = buildEmailAddress(); // Regenerate email if name changes
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
        this.email = buildEmailAddress(); // Regenerate email if name changes
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) { // Renamed to follow JavaBean conventions
        this.password = password;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
        this.email = buildEmailAddress(); // Regenerate email if department changes
    }

    public String getEmail() {
        return email;
    }

    public int getMailboxCapacity() {
        return mailboxCapacity;
    }

    public void setMailboxCapacity(int mailboxCapacity) {
        this.mailboxCapacity = mailboxCapacity;
    }

    public String getAlternateEmail() {
        return alternateEmail;
    }

    public void setAlternateEmail(String alternateEmail) {
        this.alternateEmail = alternateEmail;
    }

    // Display account info (renamed to follow Java naming conventions)
    public String showInfo() {
        return String.format("Display Name: %s %s%nCompany Email: %s%nMailbox Capacity: %d mb.%nAlternate Email: %s",
                firstName, lastName, email, mailboxCapacity,
                alternateEmail != null ? alternateEmail : "Not set");
    }
}

Key Improvements & Fixes

  • Constructor Error Resolution: The no-arg constructor now properly initializes firstName and lastName (either via user input or passed parameters). If Eclipse still complains, run a clean build.
  • User-Defined Names: You can now let users input their names either via the Main class or directly in the no-arg Email constructor.
  • Encapsulation: All private fields have dedicated getters/setters. When critical fields (name, department) are updated, the email address is automatically regenerated to keep data consistent.
  • Code Cleanup:
    • Renamed methods to follow Java conventions (e.g., ShowInfo → showInfo, ChangePassword → setPassword).
    • Used StringBuilder for string operations to improve performance.
    • Closed all Scanner resources to avoid memory leaks.
    • Marked constant values as final to enforce immutability.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:18:09