简体   繁体   English

多次打印ArrayList

[英]Printing an ArrayList multiple times

I'm working on the guessing method inside my hangman game. 我正在研究子手游戏中的猜测方法。 It takes a letter that the user wants to guess and checks it with each letter in the word. 它接收用户想要猜测的字母,并与单词中的每个字母一起检查。

public void checkGuess(String guessLetter)
{
    for(int i = 0; i < gameWord.length(); i++)
    {
        if(guessLetter.charAt(0) == (gameWord.charAt(i)))
        {
            hideword[i] = guessLetter.charAt(0);

        }
        else
        {
            hideword[i] = '_';
        }
    }
    System.out.println(hideword);
}

That current code gets me an input of: 当前代码使我输入:

Have another user enter a word to play with:

Apple 
 Welcome to hang man! Below is your word:

 _ _ _ _ _ Enter a letter to guess
 p

 _pp__

 Enter a letter to guess

  l

  ___l_

 Enter a letter to guess

Is there anyway to make it so it would print the "p" and the "l" together, instead of separate lines like it is? 无论如何,它会一起打印“ p”和“ l”,而不是像这样单独打印吗?

Remove: 去掉:

else
{
    hideword[i] = '_';
}

From your loop. 从您的循环。 Otherwise, the previous progress is being overwritten. 否则,先前的进度将被覆盖。 hideword should be filled with '_' when the game starts, and then modified as the game progresses. 游戏开始时, hideword应该用'_'填充,然后在游戏进行时对其进行修改。

Something like this, using Arrays.fill(char[], char) : 使用Arrays.fill(char[], char)这样的事情:

public Game(String word) {
    gameWord = word;
    hideword = new char[word.length()];
    Arrays.fill(hideword, '_'); // import java.util.Arrays;
}

public void checkGuess(String guessLetter) {
    for(int i = 0; i < gameWord.length(); i++)
        if(guessLetter.charAt(0) == (gameWord.charAt(i)))
            hideword[i] = guessLetter.charAt(0);
    System.out.println(hideword);
}

You can do it like this by just initialing the hideword by array of _ (where length of array is the total no of characters in gameWord) and removing else part from your code 您可以通过_数组 (其中数组的长度是gameWord中字符总数的总和)来初始化隐藏字,然后从代码中删除其他部分来做到这一点

public void checkGuess(String guessLetter) {
    for(int i = 0; i < gameWord.length(); i++) {
        if(guessLetter.charAt(0) == (gameWord.charAt(i))) {
            hideword[i] = guessLetter.charAt(0);
        }
    }
    System.out.println(hideword);
}

What is happening in your code that your every match is overriding the result of your first last match in the else part of your code, so if you would remove that it will work fine because we have already initialized the hideword by _ _ _ _ 您的代码中发生的情况是,您的每次匹配都将覆盖您代码其他部分的第一个匹配结果,因此,如果您将其删除,它将很好用,因为我们已经通过_ _ _初始化了Hideword

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM