2010-07-15 38 views
0

我已經將字符串參數放置在名爲methodASet的方法頭中。是否可以在正文中使用這個字符串參數,並返回參數中的單詞作爲一個集合?如果是這樣,我該怎麼做?謝謝。針對java的數組靜態方法頭幫助的字符串參數

public class MyMates { 

private static Set<String> names; 
private static String[] name1 = null; 
private static String[] name2 = null; 
private static String[] name3 = null; 


public MyMates() { 
    methodASet(); // (2) but I then get a error message "methodASet(java.lang.String) in myMates cannot applied to() 
    names = new TreeSet<String>(); 
} 

public static void methodASet(String aTemp) { 

    name1 = new String[]{"Amy", "Jose", "Jeremy", "Alice", "Patrick"}; 
    name2 = new String[]{"Alan", "Amy", "Jeremy", "Helen", "Alexi"}; 
    name3 = new String[]{"Adel", "Aaron", "Amy", "James", "Alice"}; 

    return aTemp; // (1) is it like this? 
} 

回答

1

這是你怎麼想aTemp添加一個字符串到現有的一組:

static Set<String> names = new TreeSet<String>(); 

public static void addToNames(String aTemp) { 
    names.add(aTemp); 
} 

您可以用做名字數組也是如此。我展示了簡單的方法:

static Set<String> names = new TreeSet<String>(); 

public static void addToNames(String[] manyNames) { 
    for(String name:manyNames) 
    names.add(name); 
} 

的設置必須創建之前,你可以增加任何價值(否則你會得到一個NullPointerException)。 names被聲明爲一個靜態字段,所以你可以在方法體內使用它,不必返回它。

你可以使用(第二)方法是這樣的:

public static void main(String[] args) { 
    // assuming names is declared and constructed like shown above 
    String[] name1 = new String[]{"Amy", "Jose", "Jeremy", "Alice", "Patrick"}; 
    String[] name2 = new String[]{"Alan", "Amy", "Jeremy", "Helen", "Alexi"}; 
    String[] name3 = new String[]{"Adel", "Aaron", "Amy", "James", "Alice"}; 

    addToNames(name1); 
    addToNames(name2); 
    addToNames(name3); 

    // Prove that the set has no duplicates and is ordered: 
    for(String name: names) 
    System.out.println(name); 
} 

希望它能幫助!

+0

謝謝Andreas_D。我希望有一天,我可以成爲像你們一樣的優秀程序員。 – DiscoDude 2010-07-15 12:09:12

+0

難道你不認爲**靜態**設置是一個壞主意嗎?更全球的情況下,在這裏使用靜態字段/方法不是更好嗎? – 2010-07-15 15:07:39

+0

@Sylvain - 我同意,但爲了這個答案,我試圖保持與上述問題的代碼片段非常接近,只是爲了儘可能讓OP理解答案。 – 2010-07-15 15:13:58

1

你的方法methodASet()需要String作爲參數,所以當你調用該方法,你必須通過一個String給它。你試圖在沒有爭論的情況下調用它。

public MyMates() { 
    methodASet("something"); 
    // ... 
} 

此外,您methodASet()方法是void,這意味着它沒有返回值。所以你不能從方法return aTemp;。要麼刪除return語句或聲明該方法返回一個String

public static String methodASet(String aTemp) { 
    // ... 

    return aTemp; 
} 
+0

是的,這是我一直使用的一個例子。有時我不確定使用什麼類型的方法頭。謝謝Jesper。 – DiscoDude 2010-07-15 12:04:49