多个if / else语句没有产生所需的输出

时间:2014-09-15 17:27:13

标签: java if-statement

我正在尝试编写一个形成随机2个字符的程序,然后要求用户猜出这个单词。在用户输入猜测之后,程序应该用答案检查猜测。然后程序应该根据他们在nAkB形式中的猜测给用户提示,其中nA是正确位置的正确字母,而kB是正确的字母,但位置错误。我的问题是我的程序在他们是正确的字母时却没有显示提示但是在错误的位置(比如答案是aD而用户猜测Dc)输出应该是"提示:0A1B" 。这是我的getHint方法的代码:

public static String getHint(String guess, String answer){
    String hint = "No";

    if(guess.charAt(0) == answer.charAt(0) && guess.charAt(1) == answer.charAt(1)){
        hint = "You win!";
    }
    else if(guess.charAt(0) == answer.charAt(0) && guess.charAt(1) != answer.charAt(1)){
        hint = "Hint: 1A0B";

    }
    else if(guess.charAt(0) != answer.charAt(0) && guess.charAt(1) == answer.charAt(1)){
        hint = "Hint: 1A0B";

    }
    else if(guess.charAt(0) == answer.indexOf(guess.charAt(0)) && guess.charAt(1) == answer.indexOf(guess.charAt(1))){
        hint = "Hint: 0A2B";

    }
    else if(guess.charAt(0) == answer.charAt(0) && guess.charAt(1) == answer.indexOf(guess.charAt(1)) &&
            guess.charAt(1) != answer.charAt(1)){
        hint = "Hint: 1A1B";

    }
    else if(guess.charAt(1) == answer.charAt(1) && guess.charAt(0) == answer.indexOf(guess.charAt(0)) &&
            guess.charAt(0) != answer.charAt(0)){
        hint = "Hint: 1A1B";

    }
    else if(guess.charAt(0) == answer.indexOf(guess.charAt(0)) && guess.charAt(0) != answer.charAt(0) &&
            guess.charAt(1) != answer.indexOf(guess.charAt(1)) && guess.charAt(1) != answer.charAt(1)){
        hint = "Hint: 0A1B";

    }
    else if(guess.charAt(1) == answer.indexOf(guess.charAt(1)) && guess.charAt(1) != answer.charAt(1) &&
            guess.charAt(0) == answer.indexOf(guess.charAt(0)) && guess.charAt(0) != answer.charAt(0)){
        hint = "Hint: 0A1B";

    }
    else{
        hint = "Hint: 0A0B";

    }


    return hint;

它永远不会输出任何带有1B或2B的东西。它只做1A0B或0A0B。

1 个答案:

答案 0 :(得分:0)

您的问题是guess.charAt(0) == answer.indexOf(guess.charAt(0))之类的代码。 indexOf将返回字符的索引。因此,您要将字符索引(rhs)与字符(lhs)的ASCII值进行比较,并且未输入使用此if构造的indexOf语句。

相反,请考虑这样的事情:

else if(answer.indexOf(guess.charAt(0))!=-1 && answer.indexOf(guess.charAt(1)) != -1{
    hint = "Hint: 0A2B";

}

Java API开始,indexOf如果在字符串中找不到给定字符,则返回-1

相关问题