Подстрока Java переключает мои положительные индексы с отрицательными - PullRequest
2 голосов
/ 08 октября 2011

Я пришел к выводу, что JTextPanes с поддержкой HTML не поддерживает перенос слов. Поэтому я пытаюсь предоставить метод домашнего приготовления. Я опубликую это в сети, как только это будет завершено. У меня может быть не самая лучшая техника, но она должна сработать, когда это будет сделано Моя проблема по какой-то безумной (очень раздражающей) причине, когда я передаю индекс моей команде подстроки, он переключает фактическое значение с тем же значением, но с отрицательным значением, и генерирует исключение java.lang.StringIndexOutOfBoundsException. Но когда переменная отправляется в команду подстроки, она определенно положительна. Когда я подставляю переменные значениям, все работает нормально. Буду признателен за любую помощь. Я включу в него.

    String wordWrap( String oldtxt )    {

        int ishere = 0;         // the current index
        int charlen = 0;        // The current length of the current line
        int beginint = 0;       // Where the text between tags begins
        int endint = 0;         // Where the text between tags ends
        String tempstr = "";    // Where the text is 
        String newoldtxt = "";  // to work around the damned oc error
        String newtxt = "";     // The new text being built
        String divystr = "";    // Temp variable to hold a partial string
        Boolean a = true;       // Needed as temp storage variable

        newoldtxt = oldtxt;

        while( true ) {

            endint = oldtxt.indexOf( "<", endint );

            if( endint == -1 )  {

                endint = oldtxt.length();
                a = false;
            }


            ishere = endint;
            tempstr = oldtxt.substring( beginint, endint );             // Save the text in a temp string

            while( ishere > endint )
            if( tempstr.length() > ( 22 - charlen ))  {                 // Testing for a complete line

//              newtxt += tempstr.substring( ishere, 22 - charlen );        // If a line is complete a line is printed to the pane
                newtxt += tempstr.substring( ishere, 22 );      // If a line is complete a line is printed to the pane
                ishere += 22 - charlen;                                     // Bumping the current index along
                charlen = 0;
                newtxt += "<br />";                                         // Attach a line break
                if( ishere >= tempstr.length() && a == false )
                return newtxt;

            } else if( tempstr.length() < ( 22 - charlen) )  {          // Checking to see if there are fewer then 22 chars in the string

                divystr = tempstr.substring( ishere, tempstr.length() );    // Dump the rest of the substring into the rebuilt string
                newtxt += divystr;                                          // Assign the remaining tempstr characters to newtxt
                charlen += divystr.length();                                // Add stray chars to charlen

                if( a == false )
                    return newtxt;
            }

            beginint = oldtxt.indexOf( ">", ( endint ) );                       // Locate end bracke
            newtxt += oldtxt.substring( beginint, endint );             // Add tag to newtxt
        }
    }
}

1 Ответ

1 голос
/ 08 октября 2011

Когда вы делаете последний вызов substring, значение endint равно 0, что больше, чем начальный индекс, что приводит к исключению StringIndexOutOfBoundsException.

// endint is larger than beginint here
newtxt += oldtxt.substring( beginint, endint );
...