问题:
提示用户输入字符串并检查它是否为复数(以“s”或“es”结尾)。输出单词的单数形式。如果用户输入单数字,只需输出单词。
示例:
我怎么打印出没有" es"?
的单词?这是我到目前为止所尝试的内容:
System.out.println("Input a plural word: ");
String pluralWord = kb.nextLine();
if (pluralWord.substring(pluralWord.length()-2).equals("es") || pluralWord.substring(pluralWord.length()-2).equals("s"))
System.out.println("Singular version of the word:"+ );
答案 0 :(得分:0)
System.out.println("Input a plural word: ");
String pluralWord = kb.nextLine();
if(pluralWord.substring(pluralWord.length()-2).equals("es")){
System.out.println("Singular version of the word:"+ pluralWord.substring(0, pluralWord.length()-2));
}else if(pluralWord.substring(pluralWord.length()-1).equals("s")){
System.out.println("Singular version of the word:"+ pluralWord.substring(0, pluralWord.length()-1));
}else{
System.out.println("Singular version of the word:"+ pluralWord);
}
答案 1 :(得分:0)
您可以将Format String Syntax与printf
一起使用。此外,String.endsWith(String)
然后substring(0, len - 2)
和/或substring(0, len - 1)
喜欢
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Input a word: ");
String pluralWord = kb.nextLine();
if (pluralWord.endsWith("es")) {
System.out.printf("Plural %s, Singular %s%n", pluralWord,
pluralWord.substring(0, pluralWord.length() - 2));
} else if (pluralWord.endsWith("s")) {
System.out.printf("Plural %s, Singular %s%n", pluralWord,
pluralWord.substring(0, pluralWord.length() - 1));
} else {
System.out.printf("Singular %s%n", pluralWord);
}
}
答案 2 :(得分:0)
System.out.println("Input a plural word: ");
String pluralWord = kb.nextLine();
if(pluralWord.length() > 1 && plurpluralWord.substring(pluralWord.length()- 2).equals("es") {
System.out.println("Singular version of the word:"+
pluralWord.substring(0 , pluralWord.length()-2));
}else if (pluralWord.length() > 0 && pluralWord.substring(pluralWord.length()- 1).equals("s")){
System.out.println("Singular version of the word:"+ pluralWord.substring(0 , pluralWord.length()-1));
}else{
System.out.println("Singular version of the word:"+ pluralWord);
}