How to Fix a Wordly Guess Game Error StringIndexOutOfBoundsException

I was building a simple Wordle style game error using Java Swing. The idea was straightforward let the player enter a five letter word, compare it against a random five-letter word selected from a .txt file, and highlight each letter based on correctness.

When I hardcoded the target word like this:

String check_word = "moizz";

Everything worked beautifully. The program read the user’s input, compared characters, and displayed results via colored labels green for correct position, yellow for wrong position, and gray for letters not in the word.

Then I decided to make the game dynamic. Instead of using a hardcoded word, I loaded words from a file:

BufferedReader reader = new BufferedReader(new FileReader("targetWords.txt"));

And that’s when the problem started.

The Unexpected Error

As soon as I used the file-sourced word, my game crashed with this error:

java.lang.StringIndexOutOfBoundsException: String index out of range: 5

I was confused. My word list only had five-letter words. Why was it failing?

I spent hours trying to debug this. I printed the words. I checked lengths. I even thought Java had a glitch!

What’s Causing the Error

After calming down and taking a step back, I revisited the error:

StringIndexOutOfBoundsException: String index out of range: 5

That means I tried to access a character at an index that doesn’t exist.

In Java, string indexing starts at 0, so if your word has five characters, the valid indexes are 0 to 4.

But here’s what my code did:

char first = take_word.charAt(1);
...
char fifth = take_word.charAt(5); // Out of bounds!

Boom There’s the bug.

By calling charAt(5), I was trying to access the 6th character. If the word was exactly five letters, this index didn’t exist — and Java doesn’t forgive that.

Even worse, if the input string (either user or file-based) was shorter than five characters due to whitespace or a mistake, this error would be thrown immediately.

Root Cause in the File Read Version

This issue only occurred when I used words from the file. Here’s what was happening:

  • Some lines had extra spaces, or the word had newline characters.
  • The .trim() call was missing or misused.
  • And, of course, I had that nasty charAt(5).

So it wasn’t just about bad indexing I also had to validate word lengths properly and clean up file input.

Fix and Best Practices

After learning my lesson, I rewrote the file handling and input validation logic. Here’s how I cleaned it up:

  • I only add words from the file if they’re exactly 5 letters.
  • I trimmed everything aggressively.
  • I looped through characters from index 0 to 4 — not 5.
  • I added user-friendly GUI feedback if the input is invalid.

Improve Code with More Feature

try {
BufferedReader reader = new BufferedReader(new FileReader("E:\\WordyGame\\src\\wordygame\\targetWords.txt"));
List<String> words = new ArrayList<>();
String line;

// Load and clean words from file
while ((line = reader.readLine()) != null) {
String[] wordsLine = line.trim().split("\\s+"); // Split by whitespace
for (String word : wordsLine) {
if (word.trim().length() == 5) {
words.add(word.trim().toLowerCase());
}
}
}
reader.close();

if (words.isEmpty()) {
JOptionPane.showMessageDialog(this, "No valid 5-letter words found in file!");
return;
}

// Pick a random word
Random rand = new Random();
String check_word = words.get(rand.nextInt(words.size()));
System.out.println("Target Word: " + check_word);

// Get user input
String take_word = type_word.getText().trim().toLowerCase();
System.out.println("User Word: " + take_word);

// Validate input
if (take_word.length() != 5) {
JOptionPane.showMessageDialog(this, "Only 5-letter words are allowed.");
return;
}

// Compare and update GUI
JLabel[] wordLabels = {word_1, word_2, word_3, word_4, word_5};
for (int i = 0; i < 5; i++) {
char userChar = take_word.charAt(i);
char targetChar = check_word.charAt(i);

wordLabels[i].setText(String.valueOf(userChar));

if (userChar == targetChar) {
wordLabels[i].setBackground(Color.GREEN); // Correct position
} else if (check_word.indexOf(userChar) >= 0) {
wordLabels[i].setBackground(Color.YELLOW); // Wrong position
} else {
wordLabels[i].setBackground(Color.LIGHT_GRAY); // Not found
}
}

} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "An error occurred: " + e.getMessage());
}

Extra Practice Feature to Add

Once I got the base game working, I realized there were so many ways to make it better. Here are some ideas I added to my to-do list:

  • Turn-based system (like 6 attempts)
  • Win/Loss messages
  • Timer or countdown
  • History tracking (previous guesses)
  • Dynamic feedback just like Wordle (color-coded per character)

Each of these could enhance the experience and help me sharpen my Java skills even more.

Final Thought

In the end, this small bug taught me a big lesson never assume your input is clean or the length is as expected. By properly validating data, trimming whitespace, and carefully using string indexes, I was able to fix the issue and improve my game. Debugging can be frustrating, but it’s also where the real learning happens.

Related blog posts