2013-05-17 47 views
0

我的代碼是這樣的:如何將字符串數組傳遞到另一個方法?

public class Test() { 

    String [] ArrayA = new String [5] 

    ArrayA[0] = "Testing"; 

     public void Method1() { 

      System.out.println(Here's where I need ArrayA[0]) 

     } 

    } 

我已經試過各種方法(沒有雙關語意),但沒有奏效。感謝任何幫助,我可以得到!

+0

你有主要的功能在這個類? –

回答

0

試試這個

private void Test(){ 
    String[] arrayTest = new String[4]; 
    ArrayA(arrayTest[0]); 
} 

private void ArrayA(String a){ 
    //do whatever with array here 
} 
+0

你正在傳遞完整的數組,他只需要數組中的第一個sting,爲什麼還要傳遞整個數組 –

1
public class Test { 

    String [] arrayA = new String [5]; // Your Array 

    arrayA[0] = "Testing"; 

    public Test(){ // Your Constructor 

     method1(arrayA[0]); // Calling the Method 

    } 

     public void method1 (String yourString) { // Your Method 

      System.out.println(yourString); 

     } 

    } 

在主類中,你可以叫new Test();
或者如果你想的方法,通過創建測試的一個實例,從主類叫你可以寫:

public class Test { 

    public Test(){ // Your Constructor 

     // method1(arrayA[0]); // Calling the Method // Commenting the method 

    } 

     public void method1 (String yourString) { // Your Method 

      System.out.println(yourString); 

     } 

    } 

在主類,在你main CLAS創建測試實例秒。

Test test = new Test(); 

String [] arrayA = new String [5]; // Your Array 

arrayA[0] = "Testing"; 

test.method1(arrayA[0]); // Calling the method 

然後調用你的方法。

編輯:

提示:有一個編碼標準,說從來沒有啓動methodvariable大寫。
此外,聲明類不需要()

0

如果我們正在討論關於傳遞數組的問題,爲什麼不整齊地使用可變參數:)您可以傳遞一個字符串,多個字符串或一個String []。

// All 3 of the following work! 
method1("myText"); 
method1("myText","more of my text?", "keep going!"); 
method1(ArrayA); 

public void method1(String... myArray){ 
    System.out.println("The first element is " + myArray[0]); 
    System.out.printl("The entire list of arguments is"); 
    for (String s: myArray){ 
     System.out.println(s); 
    } 
} 
0

試試這個片段: -

public class Test { 

     void somemethod() 
     { 
      String [] ArrayA = new String [5] ; 

       ArrayA[0] = "Testing"; 

       Method1(ArrayA); 
     } 
     public void Method1 (String[] A) { 

      System.out.println("Here's where I need ArrayA[0]"+A[0]); 

     } 
     public static void main(String[] args) { 
     new Test().somemethod(); 
    } 

} 

類的名稱應該從來沒有Test()

0

我不知道你正在嘗試做的。如果它是java代碼(它看起來像),那麼如果你不使用匿名類,它在語法上是錯誤的。

如果這是一個構造函數調用,然後下面的代碼:

public class Test1() { 
    String [] ArrayA = new String [5]; 
    ArrayA[0] = "Testing"; 
     public void Method1() { 
      System.out.println(Here's where I need ArrayA[0]); 
     } 
    } 

應該寫成這樣:

public class Test{ 
    public Test() { 
    String [] ArrayA = new String [5]; 
    ArrayA[0] = "Testing"; 
     Method1(ArrayA);   
    } 
    public void Method1(String[] ArrayA){ 
     System.out.println("Here's where I need " + ArrayA[0]); 
    } 
} 
+2

System.out.println(「這是我需要的地方」+ ArrayA [0]); –

+0

在java中,引號是非常重要的。我的壞:我編輯它 – dharam

+1

String [] ArrayA = new String [5]; 半結腸也是重要的:P –

相關問題