I am trying to find words in an array that end with a letter ‘a’. I thought of doing it using two for loops but I keep getting integer out of bounds error.
Could anyone tell me what i am doing wrong?
The code:
Scanner sc = new Scanner(System.in); System.out.println("Enter text: "); String text = sc.nextLine(); String[] words = text.split(" "); for (int i = 0; i < words.length; i++) { words[i] = words[i] + " "; } for (int i = 0; i < words.length ; i++) { 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]); } } }
Advertisement
Answer
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); } }