-5

我的代码需要一些帮助。我想使用 toCharArray() 方法将 String 对象转换为 char[],但我无法让它工作。

我在一个名为 Wordlist 的类中有这个函数:

static public char[] Contains(String w)
  {
     if (list.contains(w)) return w.toCharArray();
         else return null;
  }

我用字符串变量 res 调用函数:

char[] result = new char[4];
result = WordList.Contains(res); 

然后它似乎返回null,因为结果的值为null。但如果更改包含以下内容:

static public char[] Contains(String w)
      {
         if (list.contains(w)){
            System.out.println(w.toCharArray());
          }
         else return null;
      }

然后它打印字符串。这怎么可能?我的功能有什么问题?

4

1 回答 1

2

I don't know what you're trying to achieve but:

a) read about java naming conventions

b) List<> (and few others in java.util) has a method called .contains (so calling yours Contains causes confusion)

c) do you really want to return null in your "Contains" method?

d) the list (I presume you mean java.util.List) is never declared nor initialized

e) I presume res is a String. it is never declared not initialized.

This should give you an idea :

public static void main(String args[])
{

  String str = "someString";
  List<String> list = new ArrayList<String>();

  list.add(str);
  char[] charArray = containsString(str,list);
  System.out.println(charArray);
}
public static char[] containsString(String str, List<String> list)
{
   if (list.contains(str)) return str.toCharArray();
       else return null;
}
于 2013-04-22T17:53:48.413 回答