为什么这段代码永远不会返回真实?

时间:2014-01-11 05:44:25

标签: java methods

好的,所以我有这个方法,我插入的评论应该解释一切我不知道我做了什么让它不准确。我经历了几次测试,只做了一次。

//This method checks to see if a player has made a successful guess in the game of Hang Man
//For example, if the parameters are as follows:
//     letter: "e"
//     wordAsArray: {"h", "e", "l", "l", "o"}
//     guessed: {true, false, false, false, true}
//Then the guessed array would be changed to:
//      guessed: {true, true, false, false, true}
//And the method would return false
//Parameters:   letter - the letter that the user has just guessed
//              wordAsArray - an array of individual letters that are to be guessed
//              guessed - array of boolean values; a true value means the corresponding letter has been guessed
//Returns:  true - if letter matches an unguessed letter in wordAsArray
//          false - otherwise
public static boolean guess(String letter, String[] wordAsArray, boolean[] guessed) {
    boolean appearsAtLeastOnce=false;
    for(int i = 0; i<wordAsArray.length;i++)
        if(letter.equalsIgnoreCase(wordAsArray[i])){
            guessed[i] = true;
            appearsAtLeastOnce=true;
        }
    return appearsAtLeastOnce;

大部分时间我都会变得虚假而不是它应该是什么。这有什么不对? 欢迎所有建议!

1 个答案:

答案 0 :(得分:0)

你没有做你在评论中描述的内容:(给出的例子和评论(最后一行)矛盾)

前:

  信:“e”
  wordAsArray:{“h”,“e”,“L”,“L”,“o”}   猜测:{true,false,false,false,true}
  返回猜测:{true,true,false,false,true}
  返回布尔值:true //不打算使用

修改后的代码为:

public static boolean guess(String letter, String[] wordAsArray, boolean[] guessed) {
    boolean appearsAtLeastOnce=false;
    for(int i = 0; i<wordAsArray.length;i++)
        if(letter.equalsIgnoreCase(wordAsArray[i])){
            if(!guessed[i]){
              guessed[i] = true;                      
           }else{
              appearsAtLeastOnce = true;               
           }
        }
    return appearsAtLeastOnce;
}