//我需要帮助我的else if语句。如果单词以元音开头,则添加到单词末尾的方式。如果单词以辅音开头,则将辅音放在最后并添加一个。
我的问题是,如果我有一个带有元音的单词作为第一个字母,它就像有一个辅音一样贯穿其中。如果我输入“是”,我会得到“arewayreaay”而不是“areway”。
public class piglatin {
public static void main(String[] args) {
String str = IO. readString();
String answer = "";
if(str.startsWith("a"))
System.out.print(str + "way");
if(str.startsWith("e"))
System.out.print(str + "way");
if(str.startsWith("i"))
System.out.print(str + "way");
if(str.startsWith("o"))
System.out.print(str + "way");
if(str.startsWith("u"))
System.out.print(str + "way");
else{
char i = str.charAt(0);
answer = str.substring( 1, str.length());
System.out.print(answer + i + "ay");
}
}
}
答案 0 :(得分:6)
if(str.startsWith("a") || str.startsWith("e") || str.startsWith("i") ... (and so on)) {
System.out.print(str + "way");
} else{
char i = str.charAt(0);
answer = str.substring( 1, str.length());
System.out.print(answer + i + "ay");
}
或if / else if / else
说明:
// combine all the if blocks together .. if you dont it checks for vowel 'a' and prints
// 'areay' then it checks for vowel 'u' and enters the else block .. where it again
// operates on 'are' (check immutability of strings) gets charAt(0) i.e 'a' and prints
// 'rea' and since you concatenated 'ay' ... the final output = 'arewayreaay'
答案 1 :(得分:2)
请注意,每个领先的if
案例都会执行相同的工作,因此您可以将所有这些案例合并到一个分支中:
if (str.startsWith("a") || str.startsWith("e") || ...
System.out.print(str + "way");
else
{
// do the substring and append "ay"
除了折叠这些分支之外,您的问题是第一个分支后的每个if
语句都需要else
:
if(str.startsWith("a"))
System.out.print(str + "way");
else if(str.startsWith("e"))
System.out.print(str + "way");
// ...
您只需要一个分支执行。但请考虑最终if/else
中发生的情况:您已经修改了例如"are"
作为第一个 if
声明的结果。由于您没有使用链式if/else
,因此您将进入最后一组测试:
if(str.startsWith("u"))
System.out.print(str + "way");
else{
您最终会遇到else
案例,因为您的字符串不会以"u"
开头。但是你已经在早期的if
语句中处理了字符串。
答案 2 :(得分:1)
此处您所拥有的不是开关 - else
仅附加到最终if
。将每个if
替换为else if
,而不是第一个,或者结合jakub建议的条件。
答案 3 :(得分:1)
我觉得你的花括号搞砸了。它为'a'执行“if starts with”,然后对“u”执行“else”...所以你得到两者。你的意思是:
public static void main(String[] args)
{
String str = IO.readString();
String answer = "";
if (str.startsWith("a"))
System.out.print(str + "way");
else if(str.startsWith("e"))
System.out.print(str + "way");
else if(str.startsWith("i"))
System.out.print(str + "way");
else if(str.startsWith("o"))
System.out.print(str + "way");
else if(str.startsWith("u"))
System.out.print(str + "way");
else
{
char i = str.charAt(0);
answer = str.substring( 1, str.length());
System.out.print(answer + i + "ay");
}
}