Results 1 to 10 of 10
Like Tree3Likes
  • 1 Post By Tolls
  • 2 Post By gimbal2

Thread: Assign Arrays Index According to a Text File.

  1. #1
    histamineblkr is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Assign Arrays Index According to a Text File.

    Hello everyone.

    I have a method in a separate class that takes a text file as it's paramater and then assigns the first buffered readline to a String array and then the next buffered readline to a float array. I have a specific text file that will always follow this format:

    ABC <--------- Name
    13.75 <--------- Price
    DEF <--------- Name
    52.84 <--------- Price
    GHI etc...
    37.85
    KO
    80.00

    Now my problem is intializing the two arrays according to the text file. I want to be able to have a variable lenth text file. I can solve this problem by basically opening the file twice for reading and creating a counter "x", incrememting it, and dividing it in half as the array index. I know there has to be a better way that doesn't double my code like this and is much easier. I am drawing a blank here and can't think of anything that will get me that value. Is there a way to read the lines in the text file and divide that in half? Or something like that?

    Here is my code so you can see what I am having to do. It works, it just seems very sucky. The code is still in a rough working phase so don't mind weird comments or funky spacing.

    Java Code:
    void inputFile(File passedTextFile)
    {
        // Open, Read, Loop, and increment a counter just to be able
        //  to assign an indices to my arrays  
        int x = 0;
        try 
        {
            FileReader file = new FileReader(passedTextFile);
            BufferedReader buff = new BufferedReader(file);
            boolean eof = false;
            while (!eof) 
            {
                String stockLine = buff.readLine();
                if (stockLine == null)
                    eof = true;
                else
                {
                    x++;
                }
            }
            buff.close(); 
            System.out.println(x);
        }
        catch (IOException e) 
        {
            System.out.println("Error - " + e.toString());
        }
        // Assign variables
        float[] stockPrice = new float[x/2];
        String[] stockName = new String[x/2];
        int i = 0;
        //Try to read the file passed in 
        try 
        {
            // Open file reader, create buffered reader, and start the loop through read
            FileReader file = new FileReader(passedTextFile);
            BufferedReader buff = new BufferedReader(file);
            boolean eof = false;
            while (!eof) 
            {
                String stockLine = buff.readLine();
                if (stockLine == null)
                    eof = true;
                else
                {
                    // Assign String array value
                    stockName[i] = stockLine;
                }
                String priceLine = buff.readLine();
                if (priceLine == null)
                    eof = true;
                else
                {
                    // Assign float array value and increment i
                    stockPrice[i] = Float.parseFloat(priceLine);
                    i++;
                }
            }
            buff.close();
    
            // Print contents of arrays to stdout (Just a check to verify what's in my arrays)
            System.out.printf(Arrays.toString(stockName));
            System.out.printf(Arrays.toString(stockPrice));            
        } 
        catch (IOException e) 
        {
            System.out.println("Error - " + e.toString());
        }
    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Assign Arrays Index According to a Text File.

    Use a Collection, probably an ArrayList?

    And then you could look into creating a class to represent the data for each pair of String/float and so only need a single List, rather than one for Strings and one for Floats.
    gimbal2 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    histamineblkr is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Assign Arrays Index According to a Text File.

    I don't know why API style stuff is so difficult to read and understand, but I feel like I wil have to read those a few more times to fully understand them.

    Alright, I'll give it a shot and see if I understand what you mean. From reading, Collection is a group of objects know as its elements (Sounds like an Array that holds Objects?). What I didn't see was what types of elements it holds? I saw that there are Lists in Java and it states, "An ordered collection (also known as a sequence).". It sounds like a Collection just with a little more control where you can place elements and additional stipulations on it's methods... I guess. I'll have to read more on the Lists.

    Now the ArrayList is just the combination of an Array and a List? It seems what I was thinking about. I wondered if you could dynamically grow an Array to suit your needs, it seems the ArrayList does exactly this. I'll read more about this.

    Can you explain this maybe in a little simplier terms and is this what you meant in the above post?

    "Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:"

    Java Code:
    List list = Collections.synchronizedList(new ArrayList(...));
    Now for your last sentence. I am not sure how creating a class would make it so I only need one List. If a List doesn't care what type of element it has in it, wouldn't I only need one List anyway? In Python in a Dictionary you can actually match a name and price in the list and makes no difference what data type it is, it's great (If I remember correctly ). I wasn't sure what was the equivalent, but I think it is HashMap which has this syntax:

    Java Code:
    HashMap<Character, Integer> letters = new HashMap<Character, Integer>();
    I'm thinking I could just use String instead of Character, but I still have to figure out how to dynamically grow it.

    From your help, I think I have two possible solutions.

    1. I dynamically grow a Collection/List/ArrayList/HashMap (Or similar) and add my data to it.

    or

    2. If I could quickly and easily (low resources) read how many lines my .txt file contains, I could just divide that by two as the indices for an Array/List/Collection/HashMap. Weird, I just found this code but when I was googling before I only came across really complicated and long ways to count the lines in a file.

    Java Code:
    LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));
    lnr.skip(Long.MAX_VALUE);
    System.out.println(lnr.getLineNumber());
    I'm going to check this out later when I get home. I think if I implement this line reader and perhaps the ArrayList or HashMap I could have a nice solution. What do you think, do you see any potential problems with this approach?

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Assign Arrays Index According to a Text File.

    Here's the Collections Trail.
    I should probably have linked to that in the earlier post.Don't worry about synchronising unless you are planning on writing a multi-threaded app that shares Lists. I have rarely needed to use one.

    Using an ArrayList you only have to loop through the file once, and using a simple BufferedReader.
    If you wrote a class to hold the two elements then you would simply create an object of that class and add it to the List. A common mistake is to create a List to hold lots of different things. This is bad practice. The list should be a List of one particular data type, List<String> for example, or List<YourClass>.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,390
    Rep Power
    5

    Default Re: Assign Arrays Index According to a Text File.

    Quote Originally Posted by histamineblkr View Post
    but I feel like I wil have to read those a few more times to fully understand them.
    Reading documentation, white papers, articles, etc more than once is not unusual. If I really want to understand some technical article I usually
    have to read it more than once. It comes with the territory.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  6. #6
    histamineblkr is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Assign Arrays Index According to a Text File.

    Quote Originally Posted by jim829 View Post
    Reading documentation, white papers, articles, etc more than once is not unusual. If I really want to understand some technical article I usually
    have to read it more than once. It comes with the territory.

    Regards,
    Jim
    Oh I had already read them about 3-5 times. Apparently I'm slow or not informed enough to grasp it. Mainly I was having to read referenced things and then go back and read then read more referenced things. I don't mind it was just a lot at one =)

  7. #7
    histamineblkr is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Assign Arrays Index According to a Text File.

    Quote Originally Posted by Tolls View Post
    Here's the Collections Trail.
    I should probably have linked to that in the earlier post.Don't worry about synchronising unless you are planning on writing a multi-threaded app that shares Lists. I have rarely needed to use one.

    Using an ArrayList you only have to loop through the file once, and using a simple BufferedReader.
    If you wrote a class to hold the two elements then you would simply create an object of that class and add it to the List. A common mistake is to create a List to hold lots of different things. This is bad practice. The list should be a List of one particular data type, List<String> for example, or List<YourClass>.
    Thank you for the responses and I am still working on this. I currently am living in Dubai and work 5 14 hour days per week and do this in my off time around everything else I do so I may be long to respond before I get chances to tackle them. I want you to know I appreciate your help an input and will utilize it and write back with my results when I get to them.

  8. #8
    histamineblkr is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Assign Arrays Index According to a Text File.

    Quote Originally Posted by Tolls View Post
    Here's the Collections Trail.
    I should probably have linked to that in the earlier post.Don't worry about synchronising unless you are planning on writing a multi-threaded app that shares Lists. I have rarely needed to use one.

    Using an ArrayList you only have to loop through the file once, and using a simple BufferedReader.
    If you wrote a class to hold the two elements then you would simply create an object of that class and add it to the List. A common mistake is to create a List to hold lots of different things. This is bad practice. The list should be a List of one particular data type, List<String> for example, or List<YourClass>.
    Here's what I have come up with so far:

    Java Code:
    void inputFile(File passedTextFile)
    {
        try
        {            
            // Create Map with predefined references and assign to HashMap.
            Map<String, Float> stockMap;
            stockMap = new HashMap<>();
            int i = 0;
                
            // Open file reader, create buffered reader, and start the loop through read.
            FileReader file = new FileReader(passedTextFile);
            BufferedReader buff = new BufferedReader(file);
            boolean eof = false;
            while (!eof) 
            {                
                String stockLine = buff.readLine();
                String priceLine = buff.readLine();
                if (stockLine == null || priceLine == null)
                    eof = true;
                else
                {
                    // Assign values to hashmap.
                    stockMap.put(stockLine, Float.parseFloat(priceLine));
                }
            }
            buff.close();
            // Print HashMap.
            System.out.print(stockMap);
        }
        catch (IOException e) 
        {
            System.out.println("Error - " + e.toString());
        }
    }
    Reading through the Collections trail I came across the Map and HashMap. It seems predefining a Map for a String reference and a Float reference, assigning that Map to a HashMap, and then populating it with the BufferedReader gets the job done nicely. Now there are a few things I'm not exactly clear on. I noticed in a few tutorials you can have a synchronized HashMap but I'm not really sure what that accomplishes. Is it mainly for multiple threaded programs where multiple calls and operations can corrupt a Map? I think the synchronizing is quite a bit beyond my level for now.

    Also the HashMap seems to print out in a somewhat random order, not the order it was inputed in. I tried the System print way and this way:

    Java Code:
    Collection stockCollection = stockMap.entrySet();
    Iterator itr = stockCollection.iterator();
    while (itr.hasNext()) 
    {
        System.out.println(itr.next());
    }
    either one prints out something like this:

    KO=80.0
    ST=92.9
    ABC =13.75
    JKL =18.76
    PQR =22.15
    GHI =37.85
    MNO =43.61
    DEF =52.84
    but my stockList2.txt is like this:

    ABC
    13.75
    DEF
    52.84
    GHI
    37.85
    KO
    80.00
    JKL
    18.76
    MNO
    43.61
    PQR
    22.15
    ST
    92.90
    Now I realize I can sort the Map like this and get an Alphabetically sorted Map:
    Java Code:
    ...........
    buff.close();
                
     // Sort Map.
    Map<String, Float> sortedStockMap = new TreeMap<String, Float>(stockMap);
                
    // Print sorted HashMap.            
    Collection stockCollection = sortedStockMap.entrySet();
    Iterator itr = stockCollection.iterator();
    while (itr.hasNext()) 
    {
        System.out.println(itr.next());
    }
    Which produces this:

    ABC =13.75
    DEF =52.84
    GHI =37.85
    JKL =18.76
    KO=80.0
    MNO =43.61
    PQR =22.15
    ST=92.9
    This isn't bad, but say a user already has the text file sorted to their liking, how do I maintain that originally inputed order? Or is it actually in that order in the HashMap it just prints out in a seemingly random order?

    Lastly, if you see any thing that could cause me problems with using the Map and HashMap I am always up for suggestions. I'm not worried about getting a null read on the "priceLine" read that could cut off the stockLine because the text file is strictly controlled at this point. Perhaps later on I can error check something like that but the list will always be in a format of:

    stock1 name
    stock1 price
    stock2 name
    stock2 price
    stock3 name
    stock3price
    ect...

    Thank you for all your help so far Tolls.

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Assign Arrays Index According to a Text File.

    LinkedHashMap.
    That one maintains the order of the keys based on when they were entered, so when you iterate over the keys (or entryset) you get them back in the same order they went in.

    In the API for something like Map you'll see a section near the top called "All Known Implementing Classes". That gives the descendants of the class/interface. Going through those would give you an idea of what types of Map are available, and what they specialise in.

    The one thing I will sayabout the code is that resources should be closed in a finally block, so the general structure of file handling is something like:
    Java Code:
    BufferedReader br = null;
    try {
       // open the buffered reader
    } catch (etc) {
    } finally {
       if (br != null) {
          try {
             br.close();
          } catch (IOException) {
             // can usually ignore this one, but you might want to log it anyway.
          }
       }
    }
    That way, if there's an exception thrown then you ensure (as best you can) that the file is closed.
    This applies to all sorts of resources, eg database connections, so it's a good habit to get into.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Assign Arrays Index According to a Text File.

    Quote Originally Posted by Tolls View Post
    The one thing I will sayabout the code is that resources should be closed in a finally block
    or in a new Java 7 try-with-resources, to save annoying repeating boiler plate code.

    The try-with-resources Statement (The Java™ Tutorials > Essential Classes > Exceptions)
    Tolls and histamineblkr like this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Best way to assign an image file to a JLabel?
    By itsdavid in forum New To Java
    Replies: 5
    Last Post: 01-26-2013, 12:53 PM
  2. Replies: 0
    Last Post: 05-16-2011, 10:28 AM
  3. text file into arrays using StreamTokenizer
    By Spooge in forum New To Java
    Replies: 6
    Last Post: 10-19-2010, 12:35 AM
  4. Heat index arrays
    By gtamob69 in forum New To Java
    Replies: 7
    Last Post: 12-30-2009, 01:07 AM
  5. New to Java, Arrays- index out of bounds
    By Connorhj in forum New To Java
    Replies: 8
    Last Post: 12-02-2009, 09:22 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •