-3

I am very new to java. I was trying to take input from a file, and set the arguments from the file as hashmap key and value. But it returns null pointer exception on the line where i am splitting the arguments from line. This is my code :

public class hashtable{
    public static void main(String[] args) throws Exception{
        HashMap nodes = new HashMap<String,String>();
        String filename = args[0];
        FileReader file = null;
        BufferedReader reader = null;
        try{
          file = new FileReader(filename);
          reader = new BufferedReader(file);
          String line;
          line = reader.readLine();
            while(line != null){
             line = reader.readLine();
             String []arguments = line.split("\\s+");
             nodes.put(arguments[2],arguments[1]);
            }
        }
        catch(IOException e){}
        finally{
          reader.close();
        } 

        for(int i = 0 ; i < 5;i++){
            System.out.println(nodes.get(i));
        }
    }
}

where am i going wrong ? Any help would be appreciated.

1 Answers1

1

You're checking if line 1 is not null, but then you proceed to read and use line 2 instead. Move the next readLine() to the end of the loop:

line = reader.readLine();
while(line != null){
    String []arguments = line.split("\\s+");
    nodes.put(arguments[2],arguments[1]);
    line = reader.readLine();
}

Or, more conventionally, you can merge both readLine() statements into the loop condition:

while((line = reader.readLine()) != null) {
shmosel
  • 49,289
  • 6
  • 73
  • 138