You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序调试求助:查找含连续相同字母单词的代码抛出StringIndexOutOfBoundsException异常

Fixing Your Java Code for Consecutive Letter Word Detection

Let's break down the issues in your code and fix them step by step:

Key Issues in Your Current Code

  1. String Index Out-of-Bounds Error
    The inner loop for (int j = 0; j < s.length(); j++) causes the exception because when j reaches s.length() - 1, j + 1 exceeds the maximum valid index of the string (strings are 0-indexed). You need to stop the loop one position earlier: j < s.length() - 1.

  2. Incorrect Initialization of s
    Initializing s as " " adds an unwanted leading space to the first word (e.g., "I" becomes " I"), which breaks character checks and produces messy output. Initialize s as an empty string "" instead.

  3. 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.

  4. Duplicate Counting/Output
    Once you find consecutive letters in a word, your current code keeps looping and may trigger multiple count++ and print statements for the same word. You should break out of the inner loop immediately after confirming the word meets the criteria.

  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:47:43