gpt4 book ai didi

java - 我的复制构造函数出了什么问题?

转载 作者:行者123 更新时间:2023-12-01 20:26:18 25 4
gpt4 key购买 nike

Java 初学者。我一直在试图弄清楚如何为 java 项目编写构造函数之一。我将包含大部分代码以提供一些上下文。此类将由另一个包含终端菜单方法的文件访问。

// java class for keyboard I/O
import java.util.Scanner;

// declaration of the class
public class NumberList
{
//integer constant that determines the size of the array
public static final int MAX_CAPACITY = 100;

//array to store the numbers
private double [] numbers;
//the number of valid numbers currently in the NumberList
private int length;

//default constructor that initializes array to size MAX_CAPACITY and initializes all
//array values to 0, sets length to 10
public NumberList()
{
numbers = new double[MAX_CAPACITY];

int i;

for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = 0;

length = 10;
}

//outputs the numbers in the NumberList to the
//standard output screen
public void print()
{
int i;

for(i = 0; i < length-1; i++)
System.out.println(numbers[i]+ ", ");

System.out.println(numbers[i]);
}



//assignment constructor, initializes array to size 100,
//initializes length to l and sets the first l values of the list to the value n
NumberList(int l, double n)
{
numbers = new double[MAX_CAPACITY];

length = l;

int i;

for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = n;

}


//array constructor, initializes array to size 100, takes an array
//as input and completes a deep copy (element to element copy) from the array
//parameter to the numbers array
NumberList(final double[] a)
{
this.numbers = new double[a.length];
for (int i = 0; i < a.length; ++i)
{
this.numbers[i] = a[i];
}
}

上面的一切都编译得很好。不确定我是否走在正确的轨道上,或者是否需要“for”循环。

    **//copy constructor, initializes array to size 100, 
//creates a copy of parameter NumberList nl to the calling NumberList
NumberList(final NumberList nl)
{
numbers = new double[MAX_CAPACITY];

nl = new NumberList(MAX_CAPACITY);

}**

//returns the length of NumberList
public int length()
{
int length = numbers.length;
return length;
}

//returns the sum of the numbers in the NumberList
public double sum()
{
double sum = 0;

for (int i = 0; i < numbers.length; i++)
{
sum = sum + numbers[i];
}
return sum;
}

感谢我能得到的任何提示/建议。

最佳答案

复制构造函数就是:一个构造函数。因此,您正在为您新创建的新实例上进行操作。您不想创建另一个实例,只需设置this即可。

例如,在您的情况下,将当前实例的 numbers 设为源实例的 numbers 的副本,并复制 length >:

NumberList(final NumberList nl)
{
this.numbers = nl.numbers.clone();
this.length = nl.length;
}
<小时/>

(感谢 Jorn Verneeassylias 分别指出 Arrays.copyOfclone。使用 clone.)

关于java - 我的复制构造函数出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43857657/

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