In: Computer Science
Hey, I'm stuck on this assignment for AP Comp Sci Java. I don't know how to start.
An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a–z).
Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should be produced by the code segment.
fading
trailing
batting
public class JavaApplication20 {
public static void main(String[] args) {
//initialize array
String words[] = {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"};
//enhanced for loop to loop through the array
for (String word : words) {
//lastIndexOf() method returns the position of the last found occurrence
//of the substring specified in a string
if (word.lastIndexOf("ing") == word.length() - 3) {
System.out.println(word);
}
}
}
}
Code screenshot
Output