Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider this data sequence: \"fish bird reptile reptile bird bird bird mammal f

ID: 3533324 • Letter: C

Question

Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". Let's define a SINGLETON to be a data element that is not repeated immediately before or after itself in the sequence. So, here there are four SINGLETONs (the first appearance of "fish", the first appearance of "bird", "mammal", and the second appearance of "fish"). Write some code that uses a loop to read a sequence of words, terminated by the "xxxxx". The code assigns to the variable n the number of SINGLETONs that were read. (For example in the above data sequence it would assign 4 to n. Assume that n has already been declared . but not initialized . Assume that there will be at least one word before the terminating "xxxxx". ASSUME the availability of a variable , stdin , that references a Scannerobject associated with standard input.

Explanation / Answer

Using collections is wiser and efficient :


import java.util.Scanner;

import java.util.TreeSet;



public class Test

{

int n;

public static void main(String[] a)

{

System.out.println("Enter the words seperated by space and xxxxx to define end of Words");

Scanner stdin=new Scanner(System.in);

String str=stdin.nextLine();

String[] words=str.split(" ");

TreeSet<String> t=new TreeSet<String>();

for(String e:words)

{

//Duplicates are not allowed in Treeset

if(!(e.equals("xxxxx")))

{

t.add(e);

}

}

int n=t.size();

System.out.println("No of Singletons : "+n);

}

}