2016-03-04 46 views
0

A.java將數組傳遞給不同的類...閱讀NetBeans Java

public Class A 
{ 

     String a,b; 
     public static void setArray(String[] array)//This is where i want the array to come 
     { 
       array[0]=a; 
       array[1]=b 
     } 
} 

B.java

public class B 
{ 

     String[] arr1 = new String[2]; 
     arr1[0]="hello"; 
     arr1[2]="world"; 
     public static void main(String[] args) 
       { 
       A a = new A(); 
       a.setArray(arr1);//This is from where i send the array 
       } 
} 

我試圖從一個類發送一個陣列到另一個類

+0

而.....有什麼問題嗎? – csmckelvey

+0

由於某種原因...我在A類中得到空...如果我做System.out.println(a);那麼我得到空 –

+0

你得到一個NPE,因爲arr1還沒有初始化。您可以通過創建B的新實例來初始化它。 – Ayman

回答

1

我已經編輯了一下你的代碼。你的主要問題是在A類中,你正在向後分配值。查看更新的類A.我還爲您的類添加了構造函數,但這不是必需的。

public Class A { 

    String a,b; 

    // A public method with no return value 
    // and the same name as the class is a "class constructor" 
    // This is called when creating new A() 
    public A(String[] array) 
    { 
    setArray(array) // We will simply call setArray from here. 
    } 

    private void setArray(String[] array) 
    { 
    // Make sure you assign a to array[0], 
    // and not assign array[0] to a (which will clear this array) 
    a = array[0]; 
    b = array[1]; 
    } 
} 

public class B { 
    String[] arr1 = new String[2]; 
    arr1[0]="hello"; 
    arr1[2]="world"; 
    // A a; // You can even store your A here for later use. 
    public static void main(String[] args) 
    { 
    A a = new A(arr1); // Pass arr1 to constructor when creating new A() 
    } 
} 
0

由於您的類A中的字符串變量未初始化,您正在獲取NULL值。

在A類,你需要從方法消除靜電,並與一些初始化字符串a和b,像這樣:

public class A { 
    String a = "bye"; 
    String b = "bye"; 

    public void setArray(String[] array) { 
     array[0] = a; 
     array[1] = b; 
    } 
} 

在B類,你應該添加靜態到您的陣列(也可以不在靜態方法中引用一個非靜態變量)。

public class B { 
    static String[] arr1 = {"hello", "world"}; 
    public static void main(String[] args) { 
     A a = new A(); 
     a.setArray(arr1);//This is from where i send the array 
     System.out.println(arr1[0] + " " + arr1[1]); 
    } 
} 

另外,如果你要初始化的東西,你做的方式(方法外):

String[] arr1 = new String[2]; 
arr1[0]="hello"; 
arr1[2]="world"; 

你必須把塊內的初始化,像這樣:

String[] arr1 = new String[2]; 
{ 
    arr1[0] = "hello"; 
    arr1[2] = "world"; 
} 

希望這可以幫助你

+0

謝謝...它現在可用:) –

+0

不客氣,很高興它幫助:) – AlexMelgar