1
+ /*********************************************************************************
2
+ * (Name for both genders) Write a program that prompts the user to enter one of *
3
+ * the filenames described in Programming Exercise 12.31 and displays the names *
4
+ * that are used for both genders in the file. Use sets to store names and find *
5
+ * common names in two sets. Here is a sample run: *
6
+ *********************************************************************************/
7
+ import java .util .*;
8
+
9
+ public class Exercise_21_12 {
10
+
11
+ public static void main (String []args ) {
12
+ // Create a Scanner
13
+ Scanner input =new Scanner (System .in );
14
+
15
+ // Prompt the user to enter one of file names
16
+ System .out .print ("Enter a file name for baby name ranking: " );
17
+ String fileName =input .next ();
18
+
19
+ // Create to sets
20
+ Set <String >set1 =new HashSet <>();
21
+ Set <String >set2 =new HashSet <>();
22
+
23
+ try {
24
+ java .net .URL url =new java .net .URL (
25
+ "http://www.cs.armstrong.edu/liang/data/" +fileName );
26
+
27
+ // Create input file from url and add names to sets
28
+ Scanner inputStream =new Scanner (url .openStream ());
29
+ while (inputStream .hasNext ()) {
30
+ inputStream .next ();
31
+ set1 .add (inputStream .next ());
32
+ inputStream .next ();
33
+ set2 .add (inputStream .next ());
34
+ inputStream .next ();
35
+ }
36
+ }
37
+ catch (java .net .MalformedURLException ex ) {
38
+ System .out .println ("Invalid URL" );
39
+ }
40
+ catch (java .io .IOException ex ) {
41
+ System .out .println ("I/O Errors; no such file" );
42
+ }
43
+
44
+ // Display the names that are used for both genders
45
+ set1 .retainAll (set2 );
46
+ System .out .println (set1 .size () +" names used for both genders" );
47
+ System .out .print ("They are " );
48
+ for (String name :set1 ) {
49
+ System .out .print (name +" " );
50
+ }
51
+ System .out .println ();
52
+ }
53
+ }