如何在Java中存储用户输入

huangapple go评论74阅读模式
英文:

How to store user input in Java

问题

我正在制作一个简单的猜词游戏。以下代码会更新字母,以便检查猜测的字母是否正确。然而,如果猜测出第二个正确的字母,它就不会存储该字母。例如,对于单词 "moose",如果我猜测 'o',它会打印出 (#oo##),然后如果我猜测 'e',它会打印出 ####e。也许这与 else 语句有关?我在这方面还比较新,所以任何提示或文档都会有帮助。谢谢!

public static boolean updateWithGuess(char[] knownLetters,
                                      char guessedLetter,
                                      String word) {
    boolean found = false;

    for (int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == guessedLetter) {
            knownLetters[i] = guessedLetter;
            found = true;
        } else {
            knownLetters[i] = BLANK;
            found = false;
        }
    }
    return found;
}
英文:

I'm making a simple hangman game. The code below updates the letters so it's checking if the guessed letter is in the word properly. However, it won't store the letter if a second correct letter is guessed. For example, for "moose", if I guess 'o' then it will print out (#oo##), then if I guess 'e', it will print out ####e. Maybe it has something to do with the else statement? I'm fairly new to this so any tips or just documentation would help. Thanks!

 public static boolean updateWithGuess(char[] knownLetters,
                                      char guessedLetter,
                                      String word) {
	boolean found = false;

   	for(int i = 0; i &lt; word.length(); i++) {
		if(word.charAt(i) == guessedLetter) {
			knownLetters[i] = guessedLetter;
			found = true;
		}
		else {
			knownLetters[i] = BLANK;
			found = false;
		}
	} 
	return found;
}

答案1

得分: 1

我的猜想是问题不在这个方法中,而是尝试返回 char[] 数组,然后调用该方法的人将更新为该数组,在最终情况下,不关心它是否正确或不正确(除非你有某些原因不这样做)。同时,直接去掉整个 else 部分,那正是导致你的问题的原因,因为它会将其他字母清空,即使它们是正确的。

英文:

My guess is that the issue isnt in this method, Instead try returning the char[] And then the caller of the method will update to that, In the end not caring if its correct or incorrect(Unless if you have some reason not to do this). Also just take out the whole else, That is whats causing your issue because its blanking out the other letters even if they are correct.

huangapple
  • 本文由 发表于 2020年10月26日 11:55:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64531311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定