与标题相同。我的代码应该给出答案[1,3,3,1,0],但我无法让它给我任何控制台输出。我单独计算元音的代码不会给出我需要的值。它应该返回array.toString(),但不会
public static void main(String[] args) {
vowelCount("i think therefore i am");
}
public static int[] vowelCount(String sentence) {
int[] vowelsCounted = new int[5];
vowelsCounted.toString();
for (int i=0; i<sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == 'a') {
vowelsCounted[0]++;
} else if (ch == 'e') {
vowelsCounted[1]++;
} else if (ch == 'i') {
vowelsCounted[2]++;
} else if (ch == 'o') {
vowelsCounted[3]++;
} else if (ch == 'u') {
vowelsCounted[4]++;
}
}
return vowelsCounted;
}
}
我需要一些关于如何做以及为什么它不会给我答案的建议。 编辑:这已被回答,我正在使用错误的类。它已被更改为:
import java.util.Arrays;
public class Exercise17 {
public static void main(String[] args) {
System.out.println(vowelCount("i think therefore i am"));
}
public static String vowelCount(String sentence) {
int[] vowelsCounted = new int[5];
vowelsCounted.toString();
for (int i=0; i<sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == 'a') {
vowelsCounted[0]++;
} else if (ch == 'e') {
vowelsCounted[1]++;
} else if (ch == 'i') {
vowelsCounted[2]++;
} else if (ch == 'o') {
vowelsCounted[3]++;
} else if (ch == 'u') {
vowelsCounted[4]++;
}
}
return Arrays.toString(vowelsCounted) ;
}
}
我也想提一提,这是构建Java程序3第7章练习17,只是这些信息是非常有用的情况。 –
不明白你的意思应该返回array.toString()' - 你在哪里调用它? –
我的意思是说,我的方法vowelCount运行一个过程来获取一个字符串,检测字符,如果它是一个元音,那么vowelsCounted [0或1或2或3或4] ++。该数组在底部返回。这本书说,我称之为“我认为我是”的参数的方法应返回相当于vowelsCounted.toString()的方法。 –