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]);
}
}
}
CodePudding user response:
In your second for loop, you are checking against the character at the current position, not the length of the word. Change the condition to words[i].length()to fix it.
CodePudding user response:
In order to check if some words end with character a, we can do the following:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read the input
System.out.println("Enter text: ");
String text = sc.nextLine();
// Split the input by spaces
String[] words = text.split(" ");
// Iterate through the array of words and check if any of those ends with "a"
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
}
It would be simple as that, we don't really need an embedded loop.
CodePudding user response:
Try this instead
String[] words = {"apple", "ada", "cat", "material", "recursion", "stacksa"};
for (int i = 0; i < words.length; i ) {
// get each word first
String word = words[I];
int lenOfWord = word.length();
// check the last item in the word
if (word.charAt(lenOfWord - 1) == 'a') {
System.out.println("Last char is a" word);
}
}
CodePudding user response:
You've got too much code for the task, which has lead to a bug. IF you keep the code as simple as possible, you get 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 actually need to reference the array:
String text = sc.nextLine();
for (String word : text.split(" ")) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
CodePudding user response:
Other answers explain the logic via loops. Another approach to do the same could be through Java streams:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
Arrays.stream(words).filter(w -> w.endsWith("a")).forEach(System.out::println);
