2011-11-30 47 views
0

鑑於以下代碼,由於某種原因,它不會創建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); 


    } 
} 

問候 羅恩

+0

它拋出什麼異常? – bigblind

+0

你不能以這種方式初始化一個對象數組''this.arrayDots = new Dot [k];'...你必須使用for循環並初始化每個索引。 – CoolBeans

+0

您需要提供調試器在程序「崩潰」時爲您提供的堆棧跟蹤。 –

回答

2

我將你的代碼複製到我的Eclipse IDE中,並得到一個「org.eclipse.debug.core.DebugException:com.sun.jdi.ClassNotLoadedException:在檢索數組的組件類型時,未發生類型加載」。當我點擊arrayDots變量時出現異常。

您的代碼可以正常工作。調試器有問題,因爲Dot類未加載。 參見:http://www.coderanch.com/t/433238/Testing/ClassNotLoadedException-Eclipse-debugger

你可以改變你的主要如下(我知道這是不是很漂亮)

public static void main(String[] args) { 


    int k = 10; 
    double [] arr = {0,1,2,3,4,5}; 
    System.out.println("Enter you K"); 
    new Dot(); // the classloader loads the Dot class 
    MyVector vec = new MyVector(); // that line compile ,but when debugging it crashes , why ? 
    MyVector vec2 = new MyVector(arr); 


} 
+0

嗨,這是什麼意思「點類沒有加載」?我一直在C++上工作了三年,這是我在Java中的第一週,所以我是一個新手,所以請容易對我... – ron

+0

在java中,ClassLoader負責加載類。這是根據需要動態完成的,即當第一次實例化對象時。這意味着「加載」。在你的情況下,目前還沒有創建Dot對象,因此它沒有被ClassLoader加載。在我5年的Java職業生涯中,我從來沒有遇到這樣的問題;-) – Guenter

+0

好吧,現在呢?通過窗口扔Eclipse? – ron

2

你的默認構造函數是不可見的。在構造函數前添加public關鍵字。

+0

它仍然不起作用。我得到了ClassNotFoundException。 – ron

相關問題