ArrayIndexOutOfBoundsException when finding words in an array that and with a specific letter
You've got too much code for the task, which has lead to a bug creeping in and hiding in plain sight. As a general rule, keeping code as simple as possible results in less bugs.
Delete this, which you don't need.
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
And delete all of this:
for (int j = 0; j <= words[i].charAt(j); j++) {
if( words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' '){
System.out.println(words[i]);
}
}
instead basing your code on endsWith("a")
:
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
which is easy to read and understand (and thus easier to avoid bugs).
Even simpler, since you don't need to reference the array, use the result of the split directly:
String text = sc.nextLine();
for (String word : text.split(" ")) {
if (word.endsWith("a")) {
System.out.println(word);
}
}