![](/img/trans.png)
[英]trying to add two BigInterger Numbers together in a class Constructor and gettiing stackoverflow error
[英]stackoverflow error in class constructor
請原諒這可能是一個非常基本的問題,但我正在編寫一個程序來存儲員工信息,並且它可以正常工作,直到它嘗試在我的員工類中設置信息。 它給出了一個 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
}
通常,類用於將數據與功能組合在一起。 看起來Name
類只是一個String
的包裝器,沒有添加任何功能。 在你的 Java 職業生涯的這個階段,聲明String name;
可能更好String name;
在Employee
類中並一起刪除Name
類。 (請注意,這會從您的代碼中消除充滿鰻魚的氣墊船所描述的錯誤。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.