Java 获取字符串以接受字符串[]作为参数?

Java 获取字符串以接受字符串[]作为参数?,java,arrays,string,methods,Java,Arrays,String,Methods,我目前正在尝试创建一种方法,将单词转换为复数形式。在此过程中,我使用了一些使用.endsWith()方法的级联if 我有一个辅音(+y)的字符串数组,我想用它作为endsWith()方法的参数。但它说我需要将类型consonanty方法更改为String,而不是String[]。如果我这样做,我就不能做数组 我该怎么做 private String regularPluralForm(String word) { String s2 = ""; if(word.endsW

我目前正在尝试创建一种方法,将单词转换为复数形式。在此过程中,我使用了一些使用.endsWith()方法的级联if

我有一个辅音(+y)的字符串数组,我想用它作为endsWith()方法的参数。但它说我需要将类型consonanty方法更改为String,而不是String[]。如果我这样做,我就不能做数组

我该怎么做

    private String regularPluralForm(String word) {
    String s2 = "";
    if(word.endsWith("s)")) {
        s2 = "es";
    } else if(word.endsWith("x)")) {
        s2 = "es";
    } else if(word.endsWith("z")) {
        s2 = "es";
    } else if(word.endsWith("ch")) {
        s2 = "es";
    } else if(word.endsWith("sh"))  {
        s2 = "es";
    } else if(word.endsWith(consonantAndY)) {

    }
    String correctWord = word+s2;
    return correctWord;

}
private static final String[] consonantAndY = {"by","cy","dy","fy",
                                             "gy","hy","jy","ky"
                                             ,"ly","my","ny"
                                             ,"py","qy","ry","sy"
                                             ,"ty","vy","wy","xy"
                                             ,"yy","zy"};
}迭代数组

else {
  boolean matches = false;
  for(String s : constantAndY) {
   if (word.endsWith(s)) {
      matches = true;
      break;
   }
}

但是显然更好的答案是使用java 8,而不是在数组的每个元素上循环
辅音Andy
,调用
endsWith
,您可以使用正则表达式

} else if (word.matches(".*[bcdfghjklmnpqrstvwxyz]y")) {
使用Java8,您可以

if( Arrays.asList(consonantAndY).stream().anyMatch(t -> word.endsWith(t)) ){

// do something

}

可以创建一个名为
endsWith
的助手方法,该方法将数组作为参数

int consonantIndex = -1;
if (...) { ... }
else if((consonantIndex = endsWith(word, consonantAndY)) != -1) {
    s2 = consonantAndY[consonantIndex];
}

private int endsWith(String s, String... suffixes) {
    for (int i = 0; i < suffixes.length; i++) {
        if (s.endsWith(suffixes[i])) {
            return i;
        }
    }
    return -1;
}
int辅音索引=-1;
如果(…){…}
else if((辅音索引=endsWith(单词,辅音Andy))!=-1){
s2=辅音Andy[辅音索引];
}
私有int-endsWith(字符串s、字符串…后缀){
for(int i=0;i
您在数组中循环,并对每个数组调用
endsWith()
。您能详细说明一下吗?这会有什么帮助?如果你和埃尔斯是required@Michelle
matches
方法已经匹配了整个字符串。它成功了!非常感谢。“*”是做什么的?因为我注意到如果没有它,它就不能工作。点表示任何字符,而星表示“零或更多”。在这里,这基本上意味着“任何文本开始字符串”。