Java 打印LN时字符没有添加到字符串中?

Java 打印LN时字符没有添加到字符串中?,java,string,methods,char,Java,String,Methods,Char,我正在制作一个方法presentparticle,返回一个单词EnglishWord的presentparticle 当我运行程序时,英语单词以辅音结尾(第二个if语句),我声明的字符不会被添加。我做错了什么 private String ending1 = ".*[b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z]e"; private String consonant = ".*[b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y

我正在制作一个方法presentparticle,返回一个单词EnglishWord的presentparticle

当我运行程序时,英语单词以辅音结尾(第二个if语句),我声明的字符不会被添加。我做错了什么

private String ending1 = ".*[b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z]e";
private String consonant = ".*[b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z]";

public void run() {
    presentParticiple("jam");           
}

private String presentParticiple(String EnglishWord) {
    String correctWord = "";
    if (EnglishWord.endsWith(ending1)) {
        correctWord = EnglishWord.substring(0,EnglishWord.length()-1)+"ing";
    }

    else if (EnglishWord.endsWith(consonant)) {
        char ch = EnglishWord.charAt(EnglishWord.length());
        correctWord = EnglishWord.substring(0, EnglishWord.length())+ch+"ing";


    } else {
        correctWord = EnglishWord+"ing";
    }
    println(correctWord);
    return correctWord;
}

下面是一些有效的代码(结合上面的建议)


不过,您的算法有问题。例如,试试“敲打”。

字符串中的最后一个字符具有索引
length()-1
。Java中的索引在大多数情况下是从0开始的,这意味着最后一个索引将是
lengt-1
endsWith
也不使用正则表达式(和字符类
[…]
不需要任何像
这样的分隔符,因此只需编写
*[bcdfg…]
或使用集合的交集来消除您不希望出现在范围
a-z
)中的字符。此外,变量以小写字母开头。带有大写首字母的名称通常用于类名。所以,“EnglishWord”变成了“EnglishWord”。@Pshemo你对regex是什么意思?是的,我知道它是有效的,但是如果单词中有辅音,matches方法不返回true吗?现在试试看,“rue”和“raze”给出不同的结果。
public class EnglishTest
{
  public static void main (String[] args)
  {
    String[] words = { "jam", "rue", "raze", "knock", "need" };
    for (String word : words)
      presentParticiple (word);
  }

  private static final String ending1 = ".*[b-df-hj-np-tv-z]e";
  private static final String consonant = ".*[b-df-hj-np-tv-z]";

  private static String presentParticiple (String englishWord)
  {
    String correctWord = "";
    if (englishWord.matches (ending1))
      correctWord = englishWord.substring (0, englishWord.length () - 1) + "ing";
    else if (englishWord.matches (consonant))
    {
      char ch = englishWord.charAt (englishWord.length () - 1);
      correctWord = englishWord + ch + "ing";
    }
    else
      correctWord = englishWord + "ing";

    System.out.println (correctWord);
    return correctWord;
  }
}