我正在完成一项 Udacity 在线类(class)的作业,要求我们开发一种方法来识别名词的最后一个字母,然后根据该字母输出“La”、“el”、或者 ”?” + 名词。
完整的说明是您要完成SpanishWord 类中的fixNoun 方法,以便它返回前面带有以下内容的名词:
// "la " if the noun ends in "a",
// "el " if it ends in "o"
// "? " if it ends in some other letter.
编译时我似乎总是遇到所有失败。有人可以帮助我理解我做错了什么吗?
public String fixNoun(String noun) {
String determinenet= noun.substring(noun.length() - 1);
if(determinenet.equals("a")) {
System.out.println("la" + " "+noun );
}
else if ( determinenet.equals("o")) {
System.out.println( "el"+ " "+noun);
}
else {
System.out.println("?"+ " "+noun);
}
return noun;
}
最佳答案
您不会返回更改后的名词,而是返回旧的名词。在您的代码中,您必须更改
System.out.println("la" + " "+noun );
至
return("la " + noun);
等等。
固定代码如下所示:
public String fixNoun(String noun) {
String determinenet= noun.substring(noun.length() - 1);
if(determinenet.equals("a")) {
return("la" + " "+noun );
}
else if ( determinenet.equals("o")) {
return( "el"+ " "+noun);
}
else {
return("?"+ " "+noun);
}
}
}
P.S.:String 类有一个endsWith() 方法,可以为您提供字符串的最后一个字符。
所以你也可以这样编写代码:
public String fixNoun(String noun) {
if(noun.endsWith("a")) {
return("la " + noun);
else if(noun.endsWith("o")) {
return("el " + noun);
else {
return("? " + noun);
}
}
祝你作业顺利:)
关于java - 需要根据名词的最后一个字母输出前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22680920/