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;
}
感谢我能得到的任何提示/建议。
答案 0 :(得分:3)
复制构造函数就是:构造函数。因此,您正在为新创建的新实例上运行。您不想创建其他实例,只需设置this
。
例如,在您的情况下,将当前实例的numbers
作为源实例的numbers
的副本,并复制length
:
NumberList(final NumberList nl)
{
this.numbers = nl.numbers.clone();
this.length = nl.length;
}
(感谢Jorn Vernee和assylias分别指出Arrays.copyOf
和clone
。与clone
一起。)