我能做些什么来解决java.lang.StringIndexOutOfBoundsException?
我在写一个hang子手(游戏)程序,并且我有一个编码的短语,以星号显示给用户。当用户猜到一个正确的字母时,我试图改变编码的星号词组,以便它将一个星号改为用户输入字母。我使用的indexOf方法,但它不断输出-1,给我我能做些什么来解决java.lang.StringIndexOutOfBoundsException?
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.toUpperCase()
一点不意思是它也包含userGuess
。如果没有,你会得到-1。
一个简单的修正:
String userGuess = keyboard.nextLine().toUpperCase();
然后你就可以删除所有其他.toUpperCase()
呼叫,该字符串已经大写,一劳永逸。
userGuess
可能不是你的短语的一部分,按您的说法:
int index = phrase.indexOf(userGuess);
indexOf将返回-1,如果userGuess
不是phrase
一部分。因此,使用字串前面,请尝试使用:
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 if(phrase.contains(userGuess.toUpperCase()))
时,您将其转换为大写,但在检查索引int index = phrase.indexOf(userGuess);
时,您不是。
尝试在将userGuess转换为大写之后获取索引,如if条件中所示。
您验证了大写版本用户猜测的是你的字符串,但后来你indexOf()
检查不检查大写版本。将用户的猜测转换为大写,然后然后检查它是否在字符串中,以及它的索引是什么。
您必须将输入字符和单词转换为大写或小写。
相反的:
phrase.contains(userGuess.toUpperCase())
写:
phrase.toUpperCase().contains(userGuess.toUpperCase())
'phrase.indexOf(userGuess);'返回-1这意味着它没有被发现。将其更改为'phrase.indexOf(userGuess).toUpperCase();' –