![](/img/trans.png)
[英]java.lang.StringIndexOutOfBOundsException Error what did i do wrong
[英]What can I do to fix the java.lang.StringIndexOutOfBoundsException?
我正在編寫一個hangman(游戲)程序,並且有一個編碼的短語,對用戶顯示為星號。 當用戶猜測正確的字母時,我試圖更改編碼的星號短語,以便將一個星號更改為用戶輸入的字母。 我正在使用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.toUpperCase()
並不意味着它也包含userGuess
。 否則,您將得到-1。
一個簡單的解決方法:
String userGuess = keyboard.nextLine().toUpperCase();
然后,您可以.toUpperCase()
刪除所有其他.toUpperCase()
調用,因為該字符串已經大寫了。
根據您的陳述, userGuess
可能不屬於您的短語:
int index = phrase.indexOf(userGuess);
如果userGuess
不是phrase
一部分, indexOf將返回-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 if(phrase.contains(userGuess.toUpperCase()))
您正在將其轉換為大寫,但是當檢查索引時: int index = phrase.indexOf(userGuess);
你不是。
在if條件下將userGuess轉換為大寫后,嘗試獲取索引。
您已驗證用戶猜測的大寫版本已包含在字符串中,但后來您的indexOf()
檢查未檢查大寫版本。 將用戶的猜測轉換為大寫, 然后檢查它是否在字符串中以及它的索引是什么。
您必須將輸入字符和單詞都轉換為大寫或小寫。
代替 :
phrase.contains(userGuess.toUpperCase())
寫:
phrase.toUpperCase().contains(userGuess.toUpperCase())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.