Java程序调试求助:查找含连续相同字母单词的代码抛出StringIndexOutOfBoundsException异常
Let's break down the issues in your code and fix them step by step:
Key Issues in Your Current Code
String Index Out-of-Bounds Error
The inner loopfor (int j = 0; j < s.length(); j++)causes the exception because whenjreachess.length() - 1,j + 1exceeds the maximum valid index of the string (strings are 0-indexed). You need to stop the loop one position earlier:j < s.length() - 1.Incorrect Initialization of
s
Initializingsas" "adds an unwanted leading space to the first word (e.g., "I" becomes " I"), which breaks character checks and produces messy output. Initializesas an empty string""instead.Last Word Not Processed
Your code only processes words when it hits a space, but the final word in the sentence has no trailing space. This means it never gets checked for consecutive letters. You need to add a check after the main loop to handle this final word.Duplicate Counting/Output
Once you find consecutive letters in a word, your current code keeps looping and may trigger multiplecount++and print statements for the same word. You should break out of the inner loop immediately after confirming the word meets the criteria.Case Handling
You convert the entire input to uppercase, but the example output preserves the original word capitalization. We'll adjust the code to check for consecutive characters in a case-insensitive way while keeping the original word intact.
Corrected Code
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the sentence"); String str = sc.nextLine(); // Split input into words to avoid manual character collection headaches String[] words = str.split("\\s+"); StringBuilder resultWords = new StringBuilder(); int count = 0; for (String word : words) { boolean hasConsecutive = false; // Check each pair of consecutive characters in the word for (int j = 0; j < word.length() - 1; j++) { // Case-insensitive check (remove to make case-sensitive) char current = Character.toUpperCase(word.charAt(j)); char next = Character.toUpperCase(word.charAt(j + 1)); if (current == next) { hasConsecutive = true; break; // No need to check further once we find a match } } if (hasConsecutive) { count++; if (resultWords.length() > 0) { resultWords.append(", "); } resultWords.append(word); } } // Print formatted results if (count > 0) { System.out.println(resultWords); } System.out.println("There are " + count + " words that have consecutive letters."); } }
Explanation of Changes
- Using
split("\\s+"): This simplifies word extraction by splitting the input on one or more whitespace characters, avoiding edge cases like multiple spaces or trailing spaces. - Case-Insensitive Check: We convert individual characters to uppercase for comparison, so words like "AppleS" (with matching 'p's) are detected, while preserving the original word's case in output.
- Flag
hasConsecutive: This ensures we only count and add each valid word once, even if it has multiple sets of consecutive characters. - StringBuilder for Output: We build the result string cleanly with commas separating valid words, matching the example's output format.
- Graceful Edge Case Handling: The code works even if there are no valid words, avoiding empty or malformed output.
内容的提问来源于stack exchange,提问作者Kami Sama

