我不能从类中调用数组

时间:2014-12-31 14:55:55

标签: java arrays class methods

我想要的是每个单词的计数字母。然后用数组列出它。我在一个名为WordLengths的类中编写了一个方法,当我尝试调用它时。我得到[4,4,4,4,4,4,4,4,4,4]而不是[4,2,6,5]你能帮忙吗?

public class quiz3 {

   public static void main(String[] args) {
       String s;
       s = "This is really easy.";
       System.out.print(Arrays.toString(WordLengths.getArrayList(s) + " "));//The line with the problem.
   }
}


public class WordLengths {   

    private String s;

    public WordLengths(String s) {
         this.s = s;
    }

    public static int[] getArrayList(String s) {
       int i, x, j;
       x = 0;
       char c;
       int[] list = new int[10];
       for (i = 0; i <= s.length() - 1; i++) {
           c = s.charAt(i);
           if (c == ' ' ) {
               for(j = 0; j <= list.length - 1; j++) {
                  if(list[j] == 0) {
                      list[j] = x;
                  }
               } 
               x = 0;
          } else if (i == s.length() - 1) {
              x++;
              for(j = 0; j <= list.length - 1; j++) {
                  if(list[j] == 0) {
                      list[j] = x;
                  }
              }
              x = 0;
          } else 
          x++;
      }
      return list;
  }
}

4 个答案:

答案 0 :(得分:4)

从参数中删除连接的字符串:

System.out.print(Arrays.toString(WordLengths.getArrayList(s)));

参数WordLengths.getArrayList(s) + " "的类型为字符串。

答案 1 :(得分:2)

WordLengths.getArrayList(s) + " "是一个字符串。

删除+ " ",因此类型为WordLengths.getArrayList(s)int[]

答案 2 :(得分:0)

您知道,您可以将String转换为Character数组,只需将该数组的length属性作为字符数。我会试试。

String str = "testString";
char[] charArray = str.toCharArray();
System.out.println("Word Length : " + charArray.length);

答案 3 :(得分:0)

修复输出问题。

  • 将字符串拆分为单词
  • 为长度
  • 创建一个数组
  • 存储每个单词的长度

    public static int[] getArrayList(String s) {
        String[] words = s.split("\\s");
        int[] list = new int[words.length];
        for (int wordIdx = 0; wordIdx < words.length; wordIdx++) {
            list[wordIdx] = words[wordIdx].length();
        }
        return list;
    }