Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

java program that uses HashMaps to store the data for social network

In social networking websites, people link to their friends to form a social network.
Write a java program that uses HashMaps to store the data for such a network. Your
program should read from a file that specifies the network connections for different
usernames. The file should have the following format to specify a link:
source_usernamefriend_username
There should be an entry for each link, one per line. Here is a sample file for five
usernames:
iba java_guru
iba crisha
iba ducky
crisha java_guru
crisha iba
ducky java_guru
ducky iba
java_guru iba
java_guru crisha
java_guru ducky
wittless java_guru
In this network, everyone links to java_guru as a friend. iba is friends with java_
guru, crisha, and ducky. Note that links are not bidirectional; wittless links
with java_guru but java_guru does not link with wittless.
First, create a User class that has an instance variable to store the user’s name
and another instance variable that is of type HashSet<User>. The HashSet<User>
variable should contain references to the User objects that the current user links
to. For example, for the user iba there would be three entries, for java_guru,
crisha, and ducky. Second, create a HashMap<String,User> instance variable
in your main class that is used to map from a username to the corresponding User
object. Your program should do the following:
• Upon startup, read the data file and populate the HashMap and HashSet data
structures according to the links specified in the file.

• Allow the user to enter a name.
• If the name exists in the map, then output all usernames that are one link away
from the user entered.
• If the name exists in the map, then output all usernames that are two links away
from the user entered. To accomplish this in a general way, you might consider
writing a recursive subroutine.
Do not forget that your User class must override the hashCode and equals methods.

 

Answer:


/**
 * This program creates a hash map from a username to a User object.
 * The User object contains a HashSet of friends (other users) for
 * that user. We can use this list to compute a "neighborhood" of friends -
 * in this case, everyone within two links from a target user.
 */
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Question
{
	public static void main(String[] args)
	{
	   // The users HashMap maps from a username to a User object
	   HashMap<String,User> users = new HashMap<String,User>();

	   // First load the social network from the file to the map
	   try
	   {
 		   Scanner inputStream =
 		             new Scanner(new FileInputStream("network.txt"));	// CHANGE

		   // Read in each line, which is a source user and friend user
		   while (inputStream.hasNextLine())
		   {
        			String line = inputStream.nextLine( );
        			StringTokenizer wordFactory = new StringTokenizer(line);
        			// Read in two tokens from line
        			String srcUserName = wordFactory.nextToken();
        			String friendUserName = wordFactory.nextToken();
			// Add users to the map if not already there
			if (!users.containsKey(srcUserName))
			{
				users.put(srcUserName, new User(srcUserName));
			}
			if (!users.containsKey(friendUserName))
			{
				users.put(friendUserName, new User(friendUserName));
			}
			// Retrieve user object and add friend
			User srcUser = users.get(srcUserName);
			User friendUser = users.get(friendUserName);
			srcUser.addFriend(friendUser);
		   }
		   inputStream.close();
	   }
       catch(FileNotFoundException e)
       {
           System.out.println("File was not found");
           System.out.println("or could not be opened.");
       }
       catch(IOException e)
       {
           System.out.println("Error reading from file.");
       }

	   // Output what we loaded
	   System.out.print("Users loaded: ");
	   for (User u : users.values())
	   {
		   System.out.print(u.getName() + " ");
		   // Uncomment this section to show all friends
		   // for each user
		   /*
		   for (Object f : u.getFriendsArray())
		   {
			   User friendObj = (User) f;
			   System.out.print(friendObj.getName() + " ");
		   }
		   System.out.println();
		   */
	   }
	   System.out.println();

       	// Allow the user to input a name and then output the
       	// friends that are up to 2 links away
	 String name = "";
	 Scanner keyboard = new Scanner(System.in);
       	do
       	{
	       System.out.println("Enter a username and all friends");
	       System.out.println("two links or less will be displayed.");
	       System.out.println("Press enter to exit.");
		   name = keyboard.nextLine();
		   if (users.containsKey(name))
		   {
				System.out.println("Friends for " + name);
				User u = users.get(name);
				u.showFriends(2);  // Prints everyone up to 2 links away
		   }
		   else if (!name.equals(""))
		   {
				System.out.println("Name not found.");
		   }
	 }
	 while (!name.equals(""));
      }
} 

/**
 * User.java
 *
 * This class encapsulates user information.
 * It holds a username and a set of User objects
 * that this person links to as friends.
 */
import java.util.HashSet;

public class User
{
	private String username;		// User name
	private HashSet<User> friends;	// Set of friends

	/* Constructors */
	public User()
	{
		friends = new HashSet<User>();
	}

	public User(String newName)
	{
		username = newName;
		friends = new HashSet<User>();
	}

	/* Accessors and Mutators */
	public void setName(String newName)
	{
		username = newName;
	}

	public String getName()
	{
		return username;
	}

	public HashSet<User> getFriends()
	{
		return friends;
	}

	public Object[] getFriendsArray()
	{
		return friends.toArray();
	}

	/**
	* addFriend adds a new friend object to the set of friends.
	* @param newFriend User object to add to the set of friends
	*  	as a direct friend.
	*/
	public void addFriend(User newFriend)
	{
		friends.add(newFriend);
	}

	/**
	* removeFriend removes a friend object to the set of friends.
	* @param oldFriend User object to remove from the set of direct friends
	*/
	public void removeFriend(Object oldFriend)
	{
		friends.remove((User) oldFriend);
	}

	/**
	* showFriends is a wrapper method around the recursive routine
	* that shows all friends up to maxNumLinks away.
	* It adds a new variable to indicate the current number of links
	* away from the source, and it initialized to 1.
	*
	* @param maxNumLinks	Max number of links to show friends
	*/
	public void showFriends(int maxNumLinks)
	{
		showFriendsRecursive(1,maxNumLinks);
	}

	/**
	* showFriendsRecursive does all the work in
	* recursively showing all friends up to maxNumLinks away.
	* It increments curNumLinks for each link traversed
	* away from the source.
	*
	* @param curNumLinks	Current number of links from source user
	* @param maxNumLinks	Max number of links to show friends
	*/
	private void showFriendsRecursive(int curNumLinks, int maxNumLinks)
	{
		// Show all direct friends to this user
		for (User friend : friends)
		{
			System.out.println(username + " is friends with " + friend.getName() +
				" (" + curNumLinks + " links)");
			// Recurse on each friend if we haven't reached the
			// maximum number of links
			if (curNumLinks < maxNumLinks)
			{
				friend.showFriendsRecursive(curNumLinks + 1, maxNumLinks);
			}
		}
		System.out.println();
	}
}


Sample network file with nonsensical usernames.  
The notation of the username indicates how many links away from user A or B. 
  The last digit indicates the number of links away from user A or B. 
 This can be used to test outputting friends to different distances.

network.txt

A A1_1
A A2_1
A A3_1
A1_1 A11_2
A1_1 A12_2
A2_1 A21_2
A11_2 A111_3
B B1_1
B B2_1
B B3_1
B1_1 B11_2
B1_1 B12_2
B2_1 B21_2
B11_2 B111_3


8.

File: ratings.txt

7
Harry Potter and the Half-Blood Prince
4
Harry Potter and the Half-Blood Prince
5
Army of the Dead
1
Harry Potter and the Half-Blood Prince
4
Army of the Dead
2
The Uninvited
4
Pandorium
3


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!