开发者

string argument for array static method header help for java

I have placed string argument in the method header called methodASet. Is it possible to use this string argument in the body and returns the words in the argument as a set? If so how do I do this? Thanks.

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() {
    m开发者_如何学编程ethodASet(); // (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? 
}


This is how you would add a String like aTemp to an existing set:

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

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

You can do this with an array of names too. I show the easy way:

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

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

The Set has to be created before you can add any value (otherwise you'll get a NullPointerException). names is declared as a static field, so you can use it inside the method body and don't have to return it.

You could use the (second) method like this:

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);
}

Hope it helps!


Your method methodASet() takes a String as an argument, so when you call the method, you must pass a String to it. You are trying to call it without an argument.

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

Also, your methodASet() method is void, which means that it does not return a value. So you can't return aTemp; from the method. Either remove the return statement, or declare that the method returns a String:

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

    return aTemp;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜