gpt4 book ai didi

java - 如何使字符串在循环中第二次不可用?

转载 作者:行者123 更新时间:2023-12-01 07:57:48 24 4
gpt4 key购买 nike

我是这个网站的新手。我决定创建一个基于控制台的hangmaan 游戏,到目前为止我一直做得很好。我目前的问题让我陷入困境。

我试图做到这一点,以便如果用户输入了一个字母,并且它已被标记为正确或不正确。然后,程序不应让用户在 while 循环的后续迭代中再次输入相同的字母。

这些评论应该能让您更好地了解我在说什么。

有人可以帮我吗?

<小时/>
package hangMan2;

import java.io.IOException;
import java.util.Scanner;

public class mainClss {
public static void main(String[] args) {

int point = 0;
int numberOfLetterInWord;

// prompt user for input and store input into String word
System.out.println("Enter a word in lower case from the dictionary: ");
Scanner inputWord = new Scanner(System.in);
String word = inputWord.next();

// letters remaining in word equals the length of the word at the start
int lettersRemainingInWord = word.length();

for (int i = 0; i < 30; i++) {
System.out.println("\b");

}

// while points are above 7 (7 is when man is hung) and there's more
// than one letter remaining do all the following:
while (point > -7 && lettersRemainingInWord >= 1) {

//prompts user to input letter guess and stores in letter
System.out.print("\nEnter a letter for this " + word.length()
+ " letter word: ");
Scanner inputLetter = new Scanner(System.in);
String letter = inputLetter.next();

if (word.contains(letter)) {
System.out.println("Correct!");
point += 1;
System.out.println("Score: " + point);
lettersRemainingInWord -= 1;
//I need code here to remove the current letter from being able to be used again

if (lettersRemainingInWord > 0) {
continue;
}

else {
System.out.println("\nYou win!!!");
System.out.println("The word was: " + word);
break;
}

}

else {
System.out.println("Incorrect\n");
point -= 1;
System.out.println("Score: " + point);
//I need code here to remove the current letter from being able to be used again


if (lettersRemainingInWord > 0) {
continue;
}

else {
System.out.println("Game over! You lose!");
System.out.println("Score: " + point);
System.out.println("The word was: " + word);
break;
}

}

}

if (point <= -7) {
System.out.println("Game over! You lose!");
System.out.println("Score: " + point);
System.out.println("The word was: " + word);
}

}

}

最佳答案

您可以测试该字母是否在集合中。如果没有,请接受它并将其添加到集合中。如果是,则拒绝。

Set<String> usedLetters = new HashSet<String>();

boolean isUsedLetter(String letter) {
if (usedLetters.contains(letter)) {
return true;
} else {
usedLetters.add(letter);
return false;
}
}

关于java - 如何使字符串在循环中第二次不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com