简体   繁体   English

Java:在for循环中使用.charAt()时,StringIndexOutOfBoundsException

[英]Java: StringIndexOutOfBoundsException when using .charAt() in for-loop

thank you in advance for reading about my problem. 预先感谢您阅读有关我的问题。

I am making a Hangman game where I want to print out a hidden version of the current word, but I would like to update it when a correct letter is guessed (on the right spot, too). 我正在制作一个《 Hangman》游戏,我想打印出当前单词的隐藏版本,但是当我猜到正确的字母(也在正确的位置)时,我想对其进行更新。 I've been looking around StackOverflow but I just can't seem to find an explaination that I understand. 我一直在寻找StackOverflow,但似乎找不到我能理解的解释。 If someone could help me, that would be great. 如果有人可以帮助我,那就太好了。 :D :D

I'll post the for-loop that this is about. 我将发布有关此的for循环。 I can post more of the code if you might need it. 如果您需要,我可以发布更多代码。 The answerInput and guessInputString are both read from the console earlier in my code using a br.readLine() method. 早先在我的代码中使用br.readLine()方法从控制台读取了answerInput和guessInputString。

for (int i = 0; i < inputAnswer.length(); i++) {

    char inputAnswerChar = inputAnswer.charAt(i);

    char guessInputChar =guessInputString.charAt(i);

    if (inputAnswerChar == guessInputChar) {

        replacementString.replace(replacementString.charAt(i), inputAnswerChar);
    }

}

Thank you for any help that you can give me! 谢谢您能给我的任何帮助!

Your code is assuming that guessInputString and replacementString both have at least as many characters as inputAnswer , which is obviously wrong to assume, since your loop only guarantees that the i 'th character exists for the inputAnswer String. 您的代码假设guessInputStringreplacementString字符数至少与inputAnswer一样多,这显然是错误的,因为您的循环仅保证inputAnswer String的第i个字符存在。

BTW, replacementString.replace(replacementString.charAt(i), inputAnswerChar) has no effect, since it cannot change the String it is executed for (since String s are immutable). 顺便说一句, replacementString.replace(replacementString.charAt(i), inputAnswerChar)无效,因为它不能更改执行的String (因为String是不可变的)。 You must assign the new String returned by this method back to replacementString : 您必须将此方法返回的新String分配回replacementString

replacementString = replacementString.replace(replacementString.charAt(i), inputAnswerChar)

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

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