鑑於以下代碼,由於某種原因,它不會創建MyVector的實例。可能是什麼問題?出現此問題的主要的線路:爲什麼我無法創建MyVector的實例?
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);
}
}
問候 羅恩
它拋出什麼異常? – bigblind
你不能以這種方式初始化一個對象數組''this.arrayDots = new Dot [k];'...你必須使用for循環並初始化每個索引。 – CoolBeans
您需要提供調試器在程序「崩潰」時爲您提供的堆棧跟蹤。 –