Consider this data sequence: \"fish bird reptile reptile bird bird bird mammal f
ID: 3831902 • Letter: C
Question
Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". There is a CONSECUTIVE REPETITION of length 3 (the three consecutive birds) and a CONSECUTIVE REPETITION of length 2 (the two reptiles). There are also several SINGLETONs of length 1 (a singleton fish, a singleton bird, a singleton mammal, and another singleton fish). Write some code that uses a loop to read in a sequence of words, terminated by the "xxxxx". The code assigns to t the number of CONSECUTIVE REPETITIONS that were read. (For example, in the above data sequence that value would be 2.) Assume that t has already been declared but not initialized . Assume that there will be at least one word before the terminating "xxxxx". For this exercise, you may assume the maximum length of a word is 8.
Explanation / Answer
Here is your code in Java: -
import java.util.ArrayList;
import java.util.Scanner;
public class ConsRepetitions {
public static void main(String[] args) {
System.out.println("Enter the string words ending with xxxxx:");
Scanner sc = new Scanner(System.in);
String word = sc.next();
ArrayList<String> wordList = new ArrayList<>();
while (!word.equals("xxxxx")) { // checking till user enter xxxxx till
// then entering in string arraylist
wordList.add(word);
word = sc.next();
}
sc.close();
int count = 0;
String repeated = "";
for (int i = 0; i < wordList.size() - 1; i++) {// iterating arraylist
if (wordList.get(i).equals(wordList.get(i + 1)) && repeated.length() == 0) {
// checking if consecutive pairs are same and its not a three or
// more word similar pair
count++;
repeated = wordList.get(i);
} else if (!wordList.get(i).equals(wordList.get(i + 1))) {
// if word is not similar, setting repeated to empty string.
repeated = "";
}
}
System.out.println("Number of CONSECUTIVE REPETITIONS are:" + count);
}
}
Output: -
Enter the string words ending with xxxxx:
I
am
am
very
very
very
very
very
bad
guy
but
I
will
will
find
you
and
kill
you
because
I
I
hate
you
xxxxx
Number of CONSECUTIVE REPETITIONS are:4