运行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
sbwith a string first (e.g.,StringBuilder sb = new StringBuilder(str);) and ensure the index you target is between0andsb.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 loopfor (int i = str.length() - 1; i > 0; i--)skips the first character (index 0). The inner loopj > 0does the same. Change these conditions toi >= 0andj >= 0to 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
Occurencevariable for counting is risky; if you run this method multiple times, the value won't reset. Use a local variable orMap<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
StringorStringBuilderfalls within0 <= 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
相关产品推荐
相关产品推荐

