cubes cubes - 8 days ago 5
Java Question

Read from a text file and create a diagraph using a hashmap

I am trying to read from a text file and create a diagraph from it using a hashmap. Since some entries will contain multiple key worlds I am passing the key words as a list

HashMap<String, List<String>> map = new HashMap<>();
. My idea is that when
arg.length
is greater than two, there must be keywords to add to the list, so I run a for loop to add the key world to the list.

if(arg.length > 2)
{
for(int i = 2; i < arg.length; i++)
{
System.out.println(i);
keys.add(args[i]);
}


I receive an index out of bound error and I am not exactly sure why. The loop should only run when the index is greater than two, so I wouldn't expect to receive this error. Can someone please tell me why this would be?

This is the complete code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.Integer.parseInt;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Genalogies {



public static void main(String[] args) throws IOException {
HashMap<String, List<String>> map = new HashMap<>();
FileReader freader = new FileReader("Gene.txt");
BufferedReader inFile = new BufferedReader(freader);

String line;
int nodesTotal = parseInt(inFile.readLine());
while((line = inFile.readLine()) != null)
{
String[] arg = line.split(" ");
String value = arg[0];
int numChildren = parseInt(arg[1]);

List<String> keys = new ArrayList<>();

if(arg.length > 2)
{
for(int i = 2; i < arg.length; i++)
{
keys.add(args[i]);
}
}
map.put(value, keys);
}
}
}

Answer
//The problem is your line: 
keys.add(args[i]); 
//the correct variable is: arg not args. 
keys.add(arg[i]);