How do I fix this string index out of bounds error in my word game?

zeldagirl13 :

I am creating a word game as an assignment for class that randomly generates a 4-letter word using the letters w, x, y, and z and gives the user 10 tries to guess it. The problem is that when I enter 5 letters, I get a string index out of bounds error (StringIndexOutOfBoundsException) instead of printing "The length of the guess did not match the length of the word".

It says the error is in the "lett2 = Character.toLowerCase(word.charAt(wx));" line. The problem is that my TA helped me write this part of the code, so I assumed all of it was correct. What am I doing wrong?

import java.util.Random;
public class GuessingGame{

      private int remainingGuesses;
      private boolean wordFound;
      private static Random rand;
      private String word;

   public GuessingGame(){
      remainingGuesses = 10;
      wordFound = false;
      rand = new Random();
      word = generateWord();
   }
   
   public GuessingGame(int seed){
       remainingGuesses = 10;
       wordFound = false;
       rand = new Random(seed);
       word = generateWord();
     }
   
   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;
   }
   

   public boolean isOver(){
      if (remainingGuesses == 0)
        return true;
        
      else if (wordFound == true)
        return true;
        
      else 
        return false;  
        }
   
   
   public boolean isWin(){
      if (wordFound == true)
         return true;
      else
         return false;
      }
   
 
   public int getRemainingGuesses(){
      return remainingGuesses;
   }
   
   
   public void reset(){
      remainingGuesses = 10;
      wordFound = false;
      word = generateWord();
   }
   
   
   public String getWord(){
      return word;
   }
   
   
   private String generateWord(){
      String retStr = "";
      
      for (int i = 0; i < 4; ++i) {
         int randomNumber = rand.nextInt(4);
          if (randomNumber == 0) {
         retStr += "W";
    }
         else if (randomNumber == 1) {
         retStr += "X";
    }
         else if (randomNumber == 2) {
         retStr += "Y";
    } 
         else if (randomNumber == 3) {
         retStr += "Z";
    }
 }
      return retStr;
   }
   
}

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 and\nconsist of the letters 'W', 'X', 'Y', and 'Z'. Your goal\nis to guess the word within the alloted guesses. Good luck!\n\n");
      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)

Abe :

Add this "if" statement to the start of your "play" method. It will handle the "too large" case for you.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25323&siteId=1