我正在上 Java 入门类(class),我们有一个处理刽子手游戏的项目。我已经解决了大部分代码,但有一个我似乎无法解决的错误。
首先,程序会提示用户输入一个字母和一个空格,然后程序会在一系列连字符中显示一个单词,如果用户猜对了,则会显示相应连字符中的字母被所述字母取代。
出于测试目的,该词已默认为narrow
。
所以如果我猜字母 r
和空格,我猜索引 2,程序会给我:
Guess a letter: r
Guess a space: 2
Guess: --r---
我遇到的问题是,当我猜测空间的索引 3 并尝试猜测下一个 r 时,程序只给我与以前相同的输出。
我们不允许使用数组或字符串生成器,因为我们还没有讨论过它们。
这是我的变量:
// default word for testing
String blank = "narrow";
// variables to manipulate the string
String start = "";
String end = "";
String word = "";
// variables for input and output
// input is used for the user's letter guess
String input;
// space is used for the user's index guess
String space = "";
// guess is used at the end to display the word to the user and set equal to word after
// it has been manipulated
String guess = "";
这是处理字符串的代码。
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input)) {
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
我认为这与 if 语句
有关,但我尝试了一些其他的东西,但它们都没有用。任何帮助将不胜感激。
谢谢。
最佳答案
您的代码的问题是每次 blank.indexOf(input) 每次都返回 2(indexOf 返回 'r' 的第一次出现,即 2)
您可以更改条件以检查用户猜到的空格处的字符是否包含用户猜到的字母。 您可以按如下方式执行此操作:
- 维护要打印的模式。为此创建一个变量。
- 每当用户猜对时更新模式。
注意:在下面的代码中,猜测是我正在谈论的变量,它最初设置为“------”用于单词“narrow”
// check if the space has the letter you guessed
if (blank.charAt(space) == input.charAt(0)) {
// if it has just update the pattern string to also contain the new letter
guess = guess.substring(0, space) + input + guess.substring (space + 1)
您可以只打印或返回(如果它是一个方法)模式字符串。
关于java - Java 中的基本 Hangman 游戏(主要涉及字符串操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822453/