So I have a file that looks like this:
1st 2nd nth
e1, v1, 1
e1, v3, 2
e1, v4, 4
e1, v5, 7
e2, v1, 1
., ., .
., ., .
., ., .
where I want the first column to be the key of a hashmap (e1, or e2, or e3), and the value to be an ArrayList called "Ratings" that in I want the second column to have it's value (an int), inside the nth index of the arraylist.
Here is my code in it's entirety so far:
import java.util.*;
import java.io.*;
public class Setup
{
public static void Setup(String[] args)
{
String user;
int value, location;
//Create a Hashmap that holds a string key and an ArrayList value
HashMap<String, ArrayList<Integer>> userRatings = new HashMap<String, ArrayList<Integer>>();
try
{
BufferedReader bufferReader = new BufferedReader(new FileReader("Student list.txt")); //read from file
String line, sentence; //declare two string variables
String[] sData; //declare a string array (store the contents here)
line = bufferReader.readLine(); //Read the line
while (line != null) //While there is a line, do this:
{
line = bufferReader.readLine();
sData = line.split(", "); //Into the string array, enter individual values in the line split by the ", " characters
int iData[] = new int[sData.length]; //Create an int array the size of the string array
user = sData[0];
for (int i = 0; i <sData.length; i++) //fill the int array with the int-version of the string array
{
iData[i] = Integer.parseInt(sData[i]); //pass the strings as integers into the integer array
}
value = iData[1];
location = iData[2];
if(!userRatings.containsKey(user)) //The user does not have ratings.
{
ArrayList<Integer> ratings = new ArrayList<Integer>();
// ratings = userRatings.get(user);
for (int j = 0; j < 50; j++)
{
ratings.add(j);
}
System.out.println(user + " " + userRatings.get(user));
}
else //The user has ratings
{
userRatings.get(user).add(location,value);
System.out.println(user + " " + userRatings.get(user));
}
}
bufferReader.close();
} catch (FileNotFoundException e)
{
System.out.println("File does not exist or could not be found.");
}
catch (IOException e)
{
System.out.println("Can't read from file");
}
catch (NullPointerException e)
{
}
}
}
I am having a problem with modifying the contents of the arraylist.
To sum up: Every string in the 1st column of the file would have it's own key in the hashmap (userList) The program will check if it has the key, if no key exists, it will create a new arraylist as the value for the key. The arrayList will be populated with 50 indexes, of which they will contain "0". After that, the arraylist will have new values added from the file in which the integer in the second column will be added at the corresponding value of the nth column.
How would I populate the arraylist, and how would I edit it so that if I want to add a new integer at the nth index of user e6, I could?