我正在上Java的介绍课,我们有一个处理刽子手游戏的项目.我已经解决了大部分代码,但是有一个我似乎无法解决的错误.
首先,程序提示用户输入一个字母和一个他们认为字母所在的空格,然后程序显示一系列连字符中的单词,如果用户做出正确的猜测,相应连字符中的字母将替换为信上写着.
出于测试目的,该词已被默认缩小.
所以,如果我猜猜字母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(输入)每次都返回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,if-statement,string
来源: https://codeday.me/bug/20190608/1198972.html