StringIndexOutOfBoundsException: String index out of range:

6 respostas
J

Olá! Gostaria de saber dos colegas c alguém consegue visualizar algum tipo de erro no trecho de código abaixo:

FileReader Local = new FileReader(Dir + NomeArq);
            String str="";
            BufferedReader in = new BufferedReader(Local);
            str = in.readLine();
            if (str!= null){
                while (str!= null){

                    Combo.addItem(str.substring(6, str.length()));
                    str = in.readLine();
                    
                    
                }
            }
Faço a pergunta pq este trecho está retornando a mensagem de erro: "StringIndexOutOfBoundsException: String index out of range: -1". A variável str atualmente contém o seguinte:"3 MICROÔNIBUS RODOVIÁRIO".

Obrigado,

JOEL

6 Respostas

aborges

Provavelmente pq

str.length() < 6 em:

Combo.addItem(str.substring(6, str.length()));
J
smota

Nananinanão … num tem nao :shock:

Veja direitim o valor de str quando o erro ocorre pq citando o amado Javadoc

Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

E tira o while de dentro do if pq ele é desnecessário :roll:

J
"smota":
Nananinanão .... num tem nao :shock: Veja direitim o valor de str quando o erro ocorre... E tira o while de dentro do if pq ele é desnecessário
Obrigado smota! Veja o código alterado:
while (str!= null){
                    System.out.println(str);
                    System.out.println(str.length());
                    System.out.println(str.substring(Code));

                    Combo.addItem(str.substring(Code, str.length()));
                    str = in.readLine();
                    
                }

e veja o resultado:

3 MICROÔNIBUS RODOVIÁRIO
28
MICROÔNIBUS RODOVIÁRIO

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

:x

_fs

Cara, se imprimiu isso

System.out.println(str.substring(Code));

e é exatamente o que você precisa, porque não usa desta forma logo de uma vez?

J

Pessoal,
valeu pela força!
Só pra esclarecer (não explicar!) depois da velha seqüência: sair do programa, desligar a máquina e descansar algumas horas, eu executei nivamente e estava tudo funcionando.
Doidão, crazy, 13!
:?: :shock:
RESOLVIDO

Criado 20 de abril de 2004
Ultima resposta 22 de abr. de 2004
Respostas 6
Participantes 4