Java Pig拉丁语程序,开关/其他错误

Java Pig拉丁语程序,开关/其他错误,java,string,io,apache-pig,Java,String,Io,Apache Pig,//我的else if语句需要帮助。如果单词以元音开头,你就在单词的末尾加上一个字母。如果单词以一个辅音开头,你把这个辅音放在末尾,然后加上ay 我的问题是,如果我有一个单词的第一个字母是元音,它就会像辅音一样贯穿整个单词。如果我输入“are”,我会得到“arewayray”而不是“areway” 或if/else if/else 说明: // combine all the if blocks together .. if you dont it checks for vowel 'a' a

//我的else if语句需要帮助。如果单词以元音开头,你就在单词的末尾加上一个字母。如果单词以一个辅音开头,你把这个辅音放在末尾,然后加上ay

我的问题是,如果我有一个单词的第一个字母是元音,它就会像辅音一样贯穿整个单词。如果我输入“are”,我会得到“arewayray”而不是“areway”

或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'

这里没有开关-
else
仅附加到final
if
。将每个
if
替换为
else if
,而不是第一个,或者像jakub建议的那样组合条件。

请注意,每个前导
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");
// ...
您只希望执行一个分支。但是考虑一下你在最后的<代码>中发生了什么,如果你已经修改了,例如,<代码>是<<代码>,因为你的第一个代码>如果语句。由于您没有使用chained
if/else
,您将获得最后一组测试:

if(str.startsWith("u"))
    System.out.print(str + "way");
else{

由于字符串不是以
“u”
开头,因此您将以
else
为结尾。但是您已经在前面的
if
语句中处理了该字符串

我觉得你的花括号弄乱了。它执行“a”的“if开头”,但也执行“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");
    }
}

将来可以帮助减少这种混淆的方法是在
if
语句的主体周围加上大括号,即使它只有一行执行。
if(str.startsWith("u"))
    System.out.print(str + "way");
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");
    }
}