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

实现字符串反转时触发String index out of range: -1错误,求助排查

Fixing the "String index out of range: -1" Error in Your String Reverse Code

Hey there! Let's break down why you're seeing that frustrating String index out of range: -1 error when trying to reverse your string. That error pops up when your code tries to access a string index that doesn't exist—and since string indices start at 0, -1 is always invalid.

What's Causing the Issue?

From the code snippet you shared, the most likely culprit is not handling empty input and potentially letting your loop run past the valid index range. Here's the scenario:

  • If a user enters an empty string (or IO.readString() returns an empty string), str.length() becomes 0. When you calculate str.length() -1, that gives you -1. Trying to call str.charAt(-1) will immediately throw that index out of range error.
  • Even with non-empty strings, if your loop condition doesn't stop when the index hits 0, you might end up trying to access index -1 in the final iteration.

Corrected Full Code

Here's a complete, fixed version of your code with explanations:

public class april{ 
    public static void main(String [] args){
        System.out.println("What do you want backwards?");
        System.out.println("Your new word is " + reverse(IO.readString())); 
    } 

    public static String reverse(String str) {
        // First, handle empty or null input to avoid index errors
        if (str == null || str.isEmpty()) {
            return str;
        }

        // Create a char array to hold reversed characters
        char[] reversedChars = new char[str.length()];
        int originalIndex = str.length() - 1; // Start at the last valid character index
        int reversedIndex = 0; // Start at the beginning of the array

        // Loop only while we have valid indices to access
        while (originalIndex >= 0) {
            reversedChars[reversedIndex] = str.charAt(originalIndex);
            originalIndex--;
            reversedIndex++;
        }

        // Convert the char array back to a String
        return new String(reversedChars);
    }
}

Key Fixes & Explanations

  • Defensive Input Check: The if (str == null || str.isEmpty()) check ensures we don't try to process a string with no characters, which would lead to that problematic -1 index calculation.
  • Valid Index Boundaries: We start originalIndex at str.length() -1 (the last valid character in the string) and stop the loop when originalIndex hits 0—so we never try to access index -1.
  • Clear Character Placement: We populate the char array from the start using reversedIndex, which lets us build the reversed string correctly without gaps or overflows.

内容的提问来源于stack exchange,提问作者Lotun Kanji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:21:54