gpt4 book ai didi

java - 类构造函数中的堆栈溢出错误

转载 作者:行者123 更新时间:2023-12-01 06:44:45 36 4
gpt4 key购买 nike

请原谅这可能是一个非常基本的问题,但我正在编写一个程序来存储员工信息,并且它工作正常,直到它尝试在我的员工类中设置信息。它给出了一个 stackoverflow 错误,我不明白为什么。感谢您的帮助。

主类:

import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);

System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();

Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;

for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}

员工类别:

public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;

public Employee()
{

}

public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}

命名类:

public class Name 
{
public Name name;

public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}

最佳答案

导致 StackoverflowExceptions 的最常见原因是不知不觉地进行了递归,这是否发生在这里? ...

public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}

宾果:递归!

此构造函数将创建一个新的 Name 对象,其构造函数将创建一个新的 Name 对象,其构造函数将...因此您将无限期地创建新的 Name 对象,或者直到堆栈内存耗尽。解决方案:不要这样做。将名称分配给字符串:

class Name {
String name; // ***** String field!

public Name(String name)
{
this.name = name; // this.name is a String field
}

关于java - 类构造函数中的堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18421891/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com