我该怎么做才能修复 java.lang.StringIndexOutOfBoundsException?

What can I do to fix the java.lang.StringIndexOutOfBoundsException?

我正在编写一个刽子手(游戏)程序,并且我有一个向用户显示为星号的编码短语。当用户猜对一个字母时,我试图更改编码的星号短语,以便将一个星号更改为用户输入的字母。我正在使用 indexOf 方法,但它一直输出 -1 并给我

java.lang.StringIndexOutOfBoundsException
String index out of range -1

代码如下:

 System.out.print("Enter your next guess: ");
 String userGuess = keyboard.nextLine();

 System.out.println("You guessed " + userGuess.toUpperCase() + ".");
 System.out.println();
 if(phrase.contains(userGuess.toUpperCase())) {

   System.out.println("This is present in the secret phrase.");
   System.out.println();
   System.out.println("Number of wrong guesses so far: " + wrongGuesses);
   int index = phrase.indexOf(userGuess);
   System.out.print(index);
   encodedPhrase = (encodedPhrase.substring(0, index) + userGuess + encodedPhrase.substring(index + 1));
根据您的陈述,

userGuess 可能不属于您的短语:

int index = phrase.indexOf(userGuess);
如果 userGuess 不是 phrase 的一部分,

indexOf 将 return -1。所以在使用子字符串之前,尝试使用:

if (index < 0) {
   //userGuess not part of phrase
} else {
    //do get substring and other business logic
}

您还尝试使用 userGuess.toUpperCase() 进行包含,避免它的其他方法是:

int index = phrase.indexOf(userGuess.toUpperCase());

仅仅因为字符串包含 userGuess.toUpperCase() 并不意味着它也包含 userGuess。如果没有,你会得到 -1。

一个简单的修复:

String userGuess = keyboard.nextLine().toUpperCase();

然后您可以删除所有其他 .toUpperCase() 调用,因为字符串已经大写,一劳永逸。

如果我理解正确的话,你的短语是大写的。

检查用户猜测 if(phrase.contains(userGuess.toUpperCase())) 时,您正在将其转换为大写,但检查索引 int index = phrase.indexOf(userGuess); 时,您不是。

按照您的 if 条件将 userGuess 转换为大写后尝试获取索引。

您验证了用户猜测的大写版本在您的字符串中,但稍后您的indexOf()检查不是 检查大写版本。将用户的猜测转换为大写,然后然后 检查它是否在字符串中以及它的索引是什么。

您必须将输入的字符和单词都转换为大写或小写。

而不是:

phrase.contains(userGuess.toUpperCase())

写:

phrase.toUpperCase().contains(userGuess.toUpperCase())