Java 类构造函数中的stackoverflow错误
请原谅这可能是一个非常基本的问题,但我正在编写一个程序来存储员工信息,它工作正常,直到它试图在我的员工类中设置信息。它给出了一个stackoverflow错误,我不知道为什么。谢谢你的帮助 主要类别:Java 类构造函数中的stackoverflow错误,java,constructor,stack-overflow,Java,Constructor,Stack Overflow,请原谅这可能是一个非常基本的问题,但我正在编写一个程序来存储员工信息,它工作正常,直到它试图在我的员工类中设置信息。它给出了一个stackoverflow错误,我不知道为什么。谢谢你的帮助 主要类别: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner Input = new Scanner(System.in);
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 Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
StackOverflowException最常见的原因是在不知情的情况下出现递归,这是在这里发生的吗
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
宾果:递归
此构造函数将创建一个新名称对象,其构造函数将创建一个新名称对象,其构造函数将。。。因此,您将不断创建新的名称对象,直到堆栈内存耗尽为止。解决方案:不要这样做。为字符串指定名称:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
通常,类用于将数据与功能组合在一起。似乎
名称
类只是字符串
的包装,没有添加任何功能。在Java职业生涯的这一点上,最好声明字符串名在Employee
类中添加code>,并一起删除Name
类。(请注意,这将删除代码中描述的气垫船装满鳗鱼的错误。)堆栈溢出发生在哪一行?
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}