字符串数组元音方法

时间:2013-11-18 21:42:42

标签: java arrays methods

我必须在java中编写一个以String数组作为参数的方法。参数数组的每个元素都包含一个单词。该方法必须返回一个字符串数组,该数组只包含以元音A,E,I,O或U开头的参数数组中的单词。

这是我到目前为止所做的:

import java.util.Scanner;
import java.util.Arrays;    
public class VowelMethod {
public static String[]  beginsWithVowel (String   [] args  ) {
String vowel [] = new String[10];  

{

}
int count=0;
for(int i=0; i< count; i++) {  
if  ( vowel.startsWith ("a") || vowel.startsWith ("e") || vowel.startsWith ("i") ||      vowel.startsWith ("o") || s.startsWith ("u") );
return vowel;

//My error with this is that the startsWith method is only defined for String type, and not the  String[] type. 

2 个答案:

答案 0 :(得分:1)

以下是一些提示:

由于您要检查数组的每个元素,因此需要逐个访问每个元素。你在循环中这样做。循环数是元素的数量。对于每次迭代,检查当前元素是否以元音开头。如果是,请将其添加到单独的数组中,您将在函数末尾返回该数组。要访问数组的元素,请使用括号和索引。例如,args[0]指的是数组args的第一个元素。您使用相同的语法将值插入数组:

vowel[i] = args[i]会将索引i中的元素插入到索引i的元音中。

您希望循环args并将匹配项插入vowel

您可以使用动态数组,例如ArrayList,它会自动增大,以存储匹配的单词(而不是vowel)。这当然不是必要的。

请记住循环i次,其中i是数组的大小。

您可以使用集合而不是大型if语句,但这也不是必需的。

答案 1 :(得分:0)

示例代码,使用ArrayList(如Keyser所述):

public static final String vowelsRegex = "^[aeiou].*";
public static String[] beginsWithVowel(String[] args) {
    List<String> vowelled = new ArrayList<String>();
    for (String s : args)
            if (s.toLowerCase().matches(vowelsRegex)) vowelled.add(s);
    return vowelled.toArray(new String[vowelled.size()]);
}

我想指出的是,在这些情况下,使用正则表达式而不是多个逻辑运算几乎总是更好的主意。希望这会有所帮助。

相关问题