hello all

i am now about ready to pull my hair out and/or possibly worse!

i have to read a .csv file, split the 3 elements into variables and then put two of the variables into a map. i can read the file fine, i can display the variables in my test environment fine, but can i get them into the map.....nope

if anyone can tell me where i'm going wrong it would be great, as i'm ready to give up! i've read and read and read my text book and cant see where i'm going wrong. i'm not asking for the answer just a what i should do.

   /**
    * Prompts the user for a pathname and then attempts to open a stream
    * on the specified file. The method expects a file containing the details 
    * of target values in CSV format and will return a collection of TrialAdmin objects 
    * constructed from those details
    */
   public void readInTasks() 
   {
      String pathname = OUFileChooser.getFilename();
      File aFile = new File(pathname);
      BufferedReader bufferedFileReader = null;
      Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();

      try
      {

         bufferedFileReader = new BufferedReader(new FileReader(aFile));
         String currentLine = bufferedFileReader.readLine();
         //Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();         

         while (currentLine != null)
         {

            Scanner lineScanner = new Scanner(currentLine);
            lineScanner.useDelimiter(",");
            taskNumber = lineScanner.nextInt(); //return the next token as an integer
            version = lineScanner.next(); // return the next token as a string
            pitchTarget = lineScanner.nextInt(); // return the next token as a double
            System.out.println(taskNumber + " - " + pitchTarget);//check to see if file is read 
           [icode] targetMap.put(taskNumber, pitchTarget); //this is the line that doesn't work[/icode]
            currentLine = bufferedFileReader.readLine(); //get the next line
         }
      }
      catch (Exception anException)
      {
         System.out.println("Error: " + anException);
      }
      finally
      { 
         try
         {
            bufferedFileReader.close();
         }
         catch (Exception anException)
         {
            System.out.println("Error: " + anException);
         }
      }

   }

Recommended Answers

All 14 Replies

pitchTarget = lineScanner.nextInt(); // return the next token as a double
targetMap.put(taskNumber, pitchTarget); //this is the line that doesn't work

Your first line I posted doesn't make sense. The nextInt() method does not return a double, it returns an int. And your treeMap is declared as taking a K, V pair of Integer, Integer. So you won't be able to use TreeMap.put(integer, double)...

it was only the comment i'd not changed, it should return an int as the map is set up to have.....thanks for spotting that though! the file contains int,string,int so i shouldn't be using a double anyway.

so how do i put the values into the map knowing they are of the correct type?

Please check your .csv file.

it was only the comment i'd not changed, it should return an int as the map is set up to have.....thanks for spotting that though! the file contains int,string,int so i shouldn't be using a double anyway.

so how do i put the values into the map knowing they are of the correct type?

As long as you change the variable that I mentioned previously to type "int", the line that you thought wasn't working should work. So declare "pitchTarget" as int, not as double, then tell me if you're getting an error.

nope still doesn't work, leaves the map as null when i examin it.

adatapost> Show the code fragement though which you are accessing map element.

is it not in the first post? which part do you mean?

is it not in the first post? which part do you mean?

nope still doesn't work, leaves the map as null when i examin it.

Where did you examined map in your code? You said that the problem is in following line:

targetMap.put(taskNumber, pitchTarget); //this is the line that doesn't work

...and JC has explained every posibble factor where a code might improper statements written by you.

i checked it in the OUWorkspace.... if i run my code it displays the file line by line (as you would expect from the println line), but doesn't 'put' the variables into the map at each iteration of the loop. see screenshots in the attachment.

I assume you want to "put" the values here, but "get" the values in another method, right?

Well, you're declaring the map in this method, so as soon as this method is finished the map goes out of scope (i.e. doesn't exist anymore).

You need to either declare the map as an instance variable, or pass it into the method, rather than declaring it here.

i've declared it as an instance variable and created in the constructor (this was done already) but by taking the line out of the method i now get null.pointer exception.....

put it back and it works albeit not putting the variables into the map....

complete code for the class

import java.util.*;
import java.io.*;
import ou.*;

/**
 * Class TrialAdmin - write a description of the class here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class TrialAdmin
{
   /* instance variables */
   
   
   private Map<Integer, Integer> targetMap; 
   private List<Attempt> attempts; 
   //int taskNumber;
   //String version;
   //int pitchTarget;
   

   /**
    * Constructor for objects of class TrailAdmin
    */
   public TrialAdmin()
   {
      super();
      Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();
      List<Attempt> attempts = new ArrayList<Attempt>();
   }


   /* instance methods */

   /**
    * Display the targetMap on the default output
    */
   public void displayTargets()
   {
      System.out.println(targetMap);
   }
   
   
   
   

   
  /**
    * Prompts the user for a pathname and then attempts to open a stream
    * on the specified file. The method expects a file containing the details 
    * of target values in CSV format and will return a collection of TrialAdmin objects 
    * constructed from those details
    */
   public void readInTasks() 
   {
      String pathname = OUFileChooser.getFilename();
      File aFile = new File(pathname);
      BufferedReader bufferedFileReader = null;
      Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();
      int taskNumber;
      String version;
      int pitchTarget;
      try
      {
         
         bufferedFileReader = new BufferedReader(new FileReader(aFile));
         String currentLine = bufferedFileReader.readLine();
        
         
         while (currentLine != null)
         {
            
            Scanner lineScanner = new Scanner(currentLine);
            lineScanner.useDelimiter(",");
            taskNumber = lineScanner.nextInt(); //return the next token as an integer
            version = lineScanner.next(); // return the next token as a string
            pitchTarget = lineScanner.nextInt(); // return the next token as an int
            System.out.println(taskNumber + " - " + pitchTarget);//check to see if file is read 
            targetMap.put(taskNumber, pitchTarget);
            
            currentLine = bufferedFileReader.readLine(); //get the next line
         }
      }
      catch (Exception anException)
      {
         System.out.println("Error: " + anException);
      }
      finally
      { 
         try
         {
            bufferedFileReader.close();
         }
         catch (Exception anException)
         {
            System.out.println("Error: " + anException);
         }
      }
      
   }

// public void readInTasks()
// {
// this.targetMap = Test.readTargets();
// }

// public void readInAttempts()
//       {
//        String pathname = OUFileChooser.getFilename();
//        File aFile = new File(pathname);
//        BufferedReader bufferedFileReader = null;
//        
//        
//        try
//        
//        {
//           String currentLine;
//           bufferedFileReader = new BufferedReader(new FileReader(aFile));
//           
//           currentLine = bufferedFileReader.readLine();
//           
//           while (currentLine != null)
//           {
//             Scanner lineScanner = new Scanner(currentLine);
//             lineScanner.useDelimiter(",");
//             int task = lineScanner.nextInt(); //return the next token as an integer
//             Double attempt = lineScanner.nextDouble(); // return the next token as a double
//             //int target = task;
//             
//             if (attempt <= 0)
//             {
//                String pitch;
// 
//                pitch = OUDialog.request("Please enter a value for task " + task);
//                currentLine = task + "," + pitch;
//                }
//             
//             System.out.println(currentLine);
// 
//             //attempts.put(attempt);   
//             currentLine = bufferedFileReader.readLine(); //get the next line
//          }
//          
//       }
//       catch (Exception anException)
//       {
//          System.out.println("Error: " + anException);
//       }
//       finally
//       { 
//          try
//          {
//             bufferedFileReader.close();
//          }
//          catch (Exception anException)
//          {
//             System.out.println("Error: " + anException);
//          }
//       }
//       }

public void readInAttempts()
{
this.attempts = Test.readAttempts(this.targetMap);
}

}

This

private Map<Integer, Integer> targetMap;

declares it, but doesn't define it, which is fine, at this point.

This

Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();

declares and defines a new Map, local to the method that hides the instance variable.

So, either remove

Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();

and add

targetMap = new TreeMap<Integer, Integer>();

to the constructor.

Or Change

Map<Integer, Integer> targetMap = new TreeMap<Integer, Integer>();

to

if (targetMap == null) {
    targetMap = new TreeMap<Integer, Integer>();
}

but then, don't forget to check whether targetMap is null in the other methods before attempting to use it, or you may still throw a NullPointerException in one of those areas.

Your problem is you because you have to post complete code in your first post.

adatapost>masijade has solved your problem. Please post your problem in clear and precise form and If you are not sure - where is a problem in a code? then post complete code.

import java.util.*;
import java.io.*;
import ou.*;

/**
 * Class TrialAdmin - write a description of the class here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class TrialAdmin
{
   /* instance variables */
   
   
   private Map<Integer, Integer> targetMap; 
   private List<Attempt> attempts; 
   //int taskNumber;
   //String version;
   //int pitchTarget;
   

   /**
    * Constructor for objects of class TrailAdmin
    */
   public TrialAdmin()
   {
      super();
      targetMap = new TreeMap<Integer, Integer>();
      List<Attempt> attempts = new ArrayList<Attempt>();
   }


   /* instance methods */

   /**
    * Display the targetMap on the default output
    */
   public void displayTargets()
   {
      System.out.println(targetMap);
   }
   
   
  /**
    * Prompts the user for a pathname and then attempts to open a stream
    * on the specified file. The method expects a file containing the details 
    * of target values in CSV format and will return a collection of TrialAdmin objects 
    * constructed from those details
    */
   public void readInTasks() 
   {
      String pathname = OUFileChooser.getFilename();
      File aFile = new File(pathname);
      BufferedReader bufferedFileReader = null;
     if(targetMap==null)
        targetMap = new TreeMap<Integer, Integer>();
      int taskNumber;
      String version;
      int pitchTarget;
      try
      {
         
         bufferedFileReader = new BufferedReader(new FileReader(aFile));
         String currentLine = bufferedFileReader.readLine();
        
         
         while (currentLine != null)
         {
            
            Scanner lineScanner = new Scanner(currentLine);
            lineScanner.useDelimiter(",");
            taskNumber = lineScanner.nextInt(); //return the next token as an integer
            version = lineScanner.next(); // return the next token as a string
            pitchTarget = lineScanner.nextInt(); // return the next token as an int
            System.out.println(taskNumber + " - " + pitchTarget);//check to see if file is read 
            targetMap.put(taskNumber, pitchTarget);
            
            currentLine = bufferedFileReader.readLine(); //get the next line
         }
      }
      catch (Exception anException)
      {
         System.out.println("Error: " + anException);
      }
      finally
      { 
         try
         {
            bufferedFileReader.close();
         }
         catch (Exception anException)
         {
            System.out.println("Error: " + anException);
         }
      }
      
   }


public void readInAttempts()
{
this.attempts = Test.readAttempts(this.targetMap);
}

}

thanks masijade, i understand what i was doing wrong now! :)

i'm sure there'll be more requests for help though as the day goes on!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.