努力比较最后 2/3/4 个字符 Java(repl.it 018 - 条件语句练习 4)
Struggling with compare last 2/3/4 characters Java (repl.it 018 - Conditional Statement Practice 4)
亲爱的 Whosebug 社区,我正在努力完成 repl.it (018) 条件语句 4
中的一项任务
所以他们希望我这样做:
老师的指示:
为你做:
给定一个字符串变量"word",进行以下测试
如果单词以"y"结尾,打印“-ies”
如果单词以 "ey" 结尾,打印“-eys”
如果单词以 "ife" 结尾,打印“-ives”
如果上面的 none 为真,打印“-s”
最多打印一个。
我的代码如下所示:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//DO NOT CHANGE ABOVE CODE! Write your code below
if(word.endsWith("y"){
System.out.println("-ies");
}
else if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else{
System.out.println("-s");
}
}
}
当我 运行 例如我的输入是:嘿
当然,我的代码会遍历代码,看看第一个语句是否正确,是的,它是否相等,因为最后的 y = y,这是错误的!
我的问题是如何让我的代码比较最后 2 或 3 个字符,以便在我输入 Hey 时打印出正确的值。
如果我输入嘿,它应该打印出来:
-eys 而不是-ies
太
重新排序条件:
if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else{
System.out.println("-s");
}
这意味着我们提升了最具体的条件,并将不太具体的条件放在下面。
我已将 else if(word.endsWith("y"))
放在 else if
的最后一个,但在 else if
链中的哪个位置并不重要,只要它在前面条件 if(word.endsWith("ey"))
应该没问题。
由于以 "ey" 结尾是以 "y" 结尾的子集,因此您的第二个 if
永远不会成立。
将您的测试顺序更改为最具体的优先顺序:
if(word.endsWith("ey"){
System.out.println("-eys");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
亲爱的 Whosebug 社区,我正在努力完成 repl.it (018) 条件语句 4
中的一项任务所以他们希望我这样做:
老师的指示: 为你做:
给定一个字符串变量"word",进行以下测试
如果单词以"y"结尾,打印“-ies” 如果单词以 "ey" 结尾,打印“-eys” 如果单词以 "ife" 结尾,打印“-ives” 如果上面的 none 为真,打印“-s” 最多打印一个。
我的代码如下所示:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//DO NOT CHANGE ABOVE CODE! Write your code below
if(word.endsWith("y"){
System.out.println("-ies");
}
else if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else{
System.out.println("-s");
}
}
}
当我 运行 例如我的输入是:嘿
当然,我的代码会遍历代码,看看第一个语句是否正确,是的,它是否相等,因为最后的 y = y,这是错误的!
我的问题是如何让我的代码比较最后 2 或 3 个字符,以便在我输入 Hey 时打印出正确的值。
如果我输入嘿,它应该打印出来:
-eys 而不是-ies
太
重新排序条件:
if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else{
System.out.println("-s");
}
这意味着我们提升了最具体的条件,并将不太具体的条件放在下面。
我已将 else if(word.endsWith("y"))
放在 else if
的最后一个,但在 else if
链中的哪个位置并不重要,只要它在前面条件 if(word.endsWith("ey"))
应该没问题。
由于以 "ey" 结尾是以 "y" 结尾的子集,因此您的第二个 if
永远不会成立。
将您的测试顺序更改为最具体的优先顺序:
if(word.endsWith("ey"){
System.out.println("-eys");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}