随机文字游戏的玩法"String index out of bounds exception"错误



我正在创建一个单词游戏,作为类的赋值,该类使用字母w、x、y和z随机生成一个4个字母的单词,并给用户10次猜测。问题是,当我输入5个字母时,我会得到一个字符串索引越界错误(StringIndexOutOfBoundsException(,而不是打印"猜测的长度与单词的长度不匹配"。

它说错误在"lett2=Character.toLowerCase(word.charAt(wx((;"行中。问题是我的TA帮我写了这部分代码,所以我认为所有的代码都是正确的。我做错了什么?

方法代码:

public int play(String str){
char lett;
char lett2;
int total = 0;
remainingGuesses = remainingGuesses - 1;
for(int wx = 0; wx < str.length(); wx++) {
lett = Character.toLowerCase(str.charAt(wx));
lett2 = Character.toLowerCase(word.charAt(wx));
if (lett2 == lett) {
++total;
}
}
if (total == 4) {
wordFound = true;
}
return total;
}

主要代码:

import java.util.*;
public class GuessingGameMain{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
boolean again = true;
System.out.println("Welcome to Guess Me!");
System.out.println("A random word will be generated. It will be four letters long andnconsist of the letters 'W', 'X', 'Y', and 'Z'. Your goalnis to guess the word within the alloted guesses. Good luck!nn");
GuessingGame game = new GuessingGame();
//GuessingGame game = new GuessingGame(1234);
while(again){
while(!game.isOver()){
System.out.println("You have " + game.getRemainingGuesses() + " guesses left.");
System.out.println("Enter your guess:");
String guess = scan.nextLine();
int score = game.play(guess);
System.out.println("There are " + score + " correct letter placements.");
if(guess.length() != 4) {
System.out.println("The length of the guess did not match the length of the word.");
}
}
if(game.isWin()){
System.out.println("Congrats!");
} else {
System.out.println("You lose! The word was: " + game.getWord());
}
System.out.println("Would you like to play again? y/n");
if(Character.toLowerCase(scan.nextLine().charAt(0)) == 'n'){
again = false;
} else {
game.reset();
}
}
System.out.println("Goodbye!");
}
}

例外:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at GuessingGame.play(GuessingGame.java:34)
at GuessingGameMain.main(GuessingGameMain.java:21)

将这个"if"语句添加到"play"方法的开头。它会为你处理"太大"的案子。

if(str.length() > 4)
{
System.out.println("Warning! Too many characters detected. Only reading top 4");
str = str.substring(0,3);
}

相关内容

最新更新