【发布时间】:2012-01-10 03:57:49
【问题描述】:
鉴于以下代码,由于某种原因,它不会创建 MyVector 的实例。可能是什么问题?问题出现在 Main 行:
MyVector vec = new MyVector();
但是,当我使用另一个构造函数创建 MyVector 的实例时:
MyVector vec2 = new MyVector(arr);
它编译并分配实例。
类点:
public class Dot {
private double dotValue;
public Dot(double dotValue)
{
this.dotValue = dotValue;
}
public double getDotValue()
{
return this.dotValue;
}
public void setDotValue(double newDotValue)
{
this.dotValue = newDotValue;
}
public String toString()
{
return "The Dot's value is :" + this.dotValue;
}
}
类 MyVector
public class MyVector {
private Dot[] arrayDots;
MyVector()
{
int k = 2;
this.arrayDots = new Dot[k];
}
public MyVector(int k)
{
this.arrayDots = new Dot[k];
int i = 0;
while (i < k)
arrayDots[i].setDotValue(0);
}
public MyVector(double array[])
{
this.arrayDots = new Dot[array.length];
int i = 0;
while (i < array.length)
{
this.arrayDots[i] = new Dot(array[i]);
i++;
}
}
}
和主要
public class Main {
public static void main(String[] args) {
int k = 10;
double [] arr = {0,1,2,3,4,5};
System.out.println("Enter you K");
MyVector vec = new MyVector(); // that line compile ,but when debugging it crashes , why ?
MyVector vec2 = new MyVector(arr);
}
}
问候 罗恩
【问题讨论】:
-
抛出什么异常?
-
您不能以这种方式初始化对象数组
this.arrayDots = new Dot[k];...您必须使用for循环并初始化每个索引。 -
您需要提供程序“崩溃”时调试器提供给您的堆栈跟踪。
-
@CoolBeans - 实际上,您可以那样初始化它。只是您将其初始化为所有
null...这可能不是您想要/需要的。 -
@StephenC - 对,这就是我的意思。感谢您澄清它:)
标签: java constructor