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

运行Java代码时遭遇java.lang.StringIndexOutOfBoundsException,如何修复?

Fixing java.lang.StringIndexOutOfBoundsException in Your Code

Hey there! Let's break down why you're hitting this exception and fix your code step by step.

1. The Direct Cause of the Exception

The immediate issue throwing StringIndexOutOfBoundsException is this line:

System.out.println(sb.deleteCharAt(3));

You initialized StringBuilder sb = new StringBuilder(); which creates an empty builder (length = 0). Trying to delete a character at index 3 is impossible—valid indices for an empty builder only range from 0 to -1 (which doesn't exist).

To fix this:

  • Remove this line if it's leftover test code, or
  • Initialize sb with a string first (e.g., StringBuilder sb = new StringBuilder(str);) and ensure the index you target is between 0 and sb.length() - 1.

2. Other Critical Issues in Your Code

Your code is incomplete and has a few bugs that will cause unexpected behavior:

  • Incorrect loop ranges:
    Your outer loop for (int i = str.length() - 1; i > 0; i--) skips the first character (index 0). The inner loop j > 0 does the same. Change these conditions to i >= 0 and j >= 0 to check all characters.
  • Unfinished logic: The line sb.d... cuts off—if you're trying to track duplicates or build a result string, you'll need to complete this code block.
  • Static variable misuse: Using a static Occurence variable for counting is risky; if you run this method multiple times, the value won't reset. Use a local variable or Map<Character, Integer> instead for per-string counting.

Example Fixed Code (For Character Occurrence Tracking)

If your goal is to count how many times each character appears in the input string, here's a cleaned-up version:

import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;

class CharacterCounter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        Map<Character, Integer> occurrenceMap = new HashMap<>();

        // Count each character's occurrence
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            occurrenceMap.put(c, occurrenceMap.getOrDefault(c, 0) + 1);
        }

        // Print results
        for (Map.Entry<Character, Integer> entry : occurrenceMap.entrySet()) {
            System.out.printf("Character '%c' occurs %d times%n", entry.getKey(), entry.getValue());
        }

        sc.close();
    }
}

Key Takeaways

  • Always verify that the index you're accessing in a String or StringBuilder falls within 0 <= index < length.
  • Avoid static variables for per-operation state unless you explicitly need shared data.
  • Ensure loop conditions cover all elements you intend to process.

内容的提问来源于stack exchange,提问作者suraj chennoju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:27