Exception in thread "main" do java.lang.StringIndexOutOfBoundsException:String index out of range:-60
-
21-12-2019 - |
Pergunta
Exception in thread "main" do java.lang.StringIndexOutOfBoundsException:String index out of range:-60
Estou recebendo este erro, e eu fui tentar descobrir isso, mas eu simplesmente não consigo!Eu estou apenas começando java para toda e qualquer ajuda é muito apreciada!Aqui está o meu código:
//This method takes large amounts of text and formats
//them nicely in equal lenth lines for the console.
public void print(String a){
String textLine = a;
int x = 60;
List<String> splitText = new ArrayList<String>();
//limits the amount of characters in a printed line to 60 + the next word.
while (textLine.length() > 60) {
if (textLine.substring(x+1,1) == " "){
splitText.add(textLine.substring(0,x+1));
textLine = textLine.substring(x+2);
x = 0;
}
else {
x++;
}
}
splitText.add(textLine);
for (int y = 0; splitText.size() < y;y++){
System.out.println(splitText.get(y));
}
}
Solução
O problema é que você está tentando chamar substring(beginIndex, endIndex)
com os parâmetros:
beginIndex = x + 1 = 61
endIndex = 1
De acordo com a substring
docs:
Retorna uma nova string que é uma subseqüência de caracteres da cadeia de caracteres.A subseqüência de caracteres começa especificado beginIndex e estende-se para o caráter na índice de endIndex - 1.Assim, o comprimento da subseqüência é endIndex-beginIndex.
Isto irá cair em um comprimento de 1 - 61 = -60
.Essa é a razão da Exceção:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -60 ...
Aqui estão alguns exemplos (de documentos), sobre como usar este método:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
Editar:
Outro erro (graças a @ichramm) está em for-loop
onde você está imprimindo o resultado.O condição final deve ser y < splitText.size()
for (int y = 0; y < splitText.size(); y++) {
...
}
Outras dicas
Devido ao método substring.
public String substring(int beginIndex)
ou
public String substring(int beginIndex, int endIndex)
Parâmetros :Aqui é o detalhe de parâmetros :
beginIndex -- the begin index, inclusive .
endIndex -- the end index , exclusive.`