【发布时间】:2014-12-31 14:55:54
【问题描述】:
我想要的是计算每个单词的字母。然后用数组列出它。我在一个名为 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;
}
}
【问题讨论】:
-
WordLengths.getArrayList(s) + " "是一个字符串,不能作为Arrays.toString的参数 -
在此处检查括号
System.out.print(Arrays.toString(WordLengths.getArrayList(s) + " "));。它将是Arrays.toStrin(int[] + " ")。