I'm learning Java and I don't know what is wrong here. Why is this error happening? I don't see anything wrong and that was actually working until when I wrote the line "count = 0" before the second "for" loop.
That is the error: java.lang.StringIndexOutOfBoundsException: String index out of range: 1
That's the line where the error is happening:
if(mots.get(j).startsWith(searchPhrase.substring(0,1))){
Here is the entire code:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<String> mots = new ArrayList<>();
List<String> saida = new ArrayList<>();
mots.add("un");
mots.add("deux");
mots.add("trois");
String searchPhrase = "aaasdeuxctsundesle";
int count = 0;
int countAnula = 0;
int azul = 0;
String anula = "-"; //Tem que fazer cast para char depois
String frase = searchPhrase;
for (int i = 0; i < frase.length(); i++) {
count = 0;
for (int j = 0; j < mots.size(); j++) {
if (mots.get(j).startsWith(searchPhrase.substring(0,1))) {
for (int t = 0; t < mots.get(j).length(); t++) {
if (searchPhrase.charAt(t) == mots.get(j).charAt(t)) {
azul ++;
} else {
break;
}
}
if (azul == mots.get(j).length()) {
saida.add(mots.get(j));
searchPhrase = searchPhrase.substring(mots.get(j).length());
j = 0;
azul = 0;
} else {
searchPhrase = searchPhrase.substring(1);
saida.add(anula);
j = 0;
azul = 0;
}
} else {
count ++;
}
}
if (count == mots.size()) {
searchPhrase = searchPhrase.substring(1);
saida.add(anula);
count = 0;
}
}
for (int g = 0; g < saida.size(); g++) {
System.out.println(saida.get(g));
}
}
}