Page 1 of 2 12 LastLast
Results 1 to 20 of 29
Like Tree1Likes

Thread: Array Troubles

  1. #1
    shodai is offline Senior Member
    Join Date
    Apr 2012
    Posts
    106
    Rep Power
    0

    Default Array Troubles

    I am working through a text and I am supposed to complete the following tasks.
    Your ReadFiles.java class requires the following methods:

    Method: check to see if the file exists

    Method: find number of rows in csv file

    Method: Converts the csv file to a mutli-dimensional array

    Method: PrintArray

    Method: Return array using a get method

    Create a file DataAnalyzer.java. This file will be used to call the methods in ReadFiles.java. Be sure to demonstrate that all of your methods work through DataAnalyzer.java.

    The problem is that it does not really provide any information on how to go about reading a file into an array. I am stuck at the third task of converting the file to an array and I have tried several ways to do this unsuccessfully. I thought that I would at least try to get things to print out (line 87) to see if I could get that to work, but all that prints in null over and over again.

    Any help would be greatly appreciated.

    Java Code:
    public class DataAnalyzer
    {
      public static void main (String[] args)
      {
        ReadFiles aReadFiles = new ReadFiles();
        aReadFiles.fileCheck();
        aReadFiles.findRows();
        aReadFiles.convertFile();
      }
    }
    Java Code:
    import java.nio.file.*;
    import static java.nio.file.AccessMode.*;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    
    public class ReadFiles
    {
      public static int numberOfRows;
      public static int rowNumber = 0;
      public static int columnNumber = 0;
      public static int newRowNumber = 0;
      public static int newColumnNumber = 0;
      String [][] myData = new String [430][7];
    
    
      public void fileCheck()
      {
        Path filePath = Paths.get("C:\\Users\\Brad\\Downloads\\FB1.csv");
        System.out.println("Path is " + filePath.toString());
        
        try
        {
          filePath.getFileSystem().provider().checkAccess(filePath, READ, EXECUTE);
          System.out.println("File can be read and executed");
        }
        
        catch (IOException e)
        {
          System.out.println ("File cannot be used for this application");
        }
      }
      
      public void findRows()
      {
        String filePath = ("C:\\Users\\Brad\\Downloads\\FB1.csv");
        
        try
        {
          BufferedReader br = new BufferedReader(new FileReader(filePath));
          StringTokenizer st = null;
          System.out.println("Your file is being analysed. This may take several minutes.");
    
          while((filePath = br.readLine()) != null)
          {
            rowNumber++;
                    
            st = new StringTokenizer(filePath, ",");
    
            columnNumber = 0;
          }
        }
        
        catch (FileNotFoundException e)
        {
          System.out.println ("Number of rows for this file cannot be found");
        } 
        
        catch (IOException e) 
        {
          System.out.println ("Number of rows for this file cannot be found");
        }
            
        System.out.println("Total Rows: " + (rowNumber));
      }
      
      public void convertFile()
      {
        String convertFilePath = ("C:\\Users\\Brad\\Downloads\\FB1.csv");
        
        try
        {
          BufferedReader br = new BufferedReader(new FileReader(convertFilePath));
          StringTokenizer st = null;
    
          while((convertFilePath = br.readLine()) != null)
          {
            newRowNumber++;
    
            st = new StringTokenizer(convertFilePath, ",");
    
            while(st.hasMoreTokens())
            {
              columnNumber++;
              System.out.println (myData[newRowNumber][newColumnNumber]);
    
            }
            newColumnNumber = 0;
          }
        }       
        catch (FileNotFoundException e) 
        {
          System.out.println("Encountered critical error. Your file has not been converted");
        } 
        catch (IOException e) 
        {
          System.out.println("Encountered critical error. Your file has not been converted");
        }
        
      }
      
      public void printArray()
      {
        
      }
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Array Troubles

    converting the file to an array
    What are the steps the program needs to take to do that?
    The first step would be to read a line from the file.
    Then what?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Array Troubles

    One challenge that you will face in reading in a CSV file into an array is that when you create the array, you have to know how many rows and columns that you will need and you won't know this until you read the data from the file. I see two possible solutions for this.

    1. Read the file twice.
    A. Once to get the maximum number of rows and columns
    B. Create the arrays once that you know how big to make them
    C. Read the data from the file a second time, this time not merely calculating the biggest row and column, but actually storing the data into the arrays.

    2. A better solution than using arrays is to use an ArrayList of ArrayLists. Unlike arrays, ArrayLists can grow to be the necessary size. So you could create the ArrayList of ArrayLists and then read the data only once.

    I would start with solution #1 and then also try solution #2 once that you have covered ArrayLists.
    Last edited by kaydell2; 02-13-2014 at 11:18 PM.

  4. #4
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,377
    Rep Power
    5

    Default Re: Array Troubles

    Quote Originally Posted by kaydell2 View Post
    One challenge that you will face in reading in a CSV file into an array is that when you create the array, you have to know how many rows and columns that you will need and you won't know this until you read the data from the file.
    Nope! You can easily reallocate the arrays dynamically. See the Arrays class. At least one greater challenge is handling embedded commas within Strings which are separated values.

    But as you said, using Lists is a better approach.

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

  5. #5
    shodai is offline Senior Member
    Join Date
    Apr 2012
    Posts
    106
    Rep Power
    0

    Default Re: Array Troubles

    The problem with using an arraylist is that the instructions are specifically to use a two dimensional array. The odd thing is that I know how to use a two dimensional array with variables that are already declared, how to get user input for an array, etc. But I cannot figure out how to write the code to get the values from the file into the array.

  6. #6
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,377
    Rep Power
    5

    Default Re: Array Troubles

    The easiest way since you are familiar with the Scanner class for console input is to have the scanner instance read the file. Just look at the API for different Scanner constructors. There are several options to read files.

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

  7. #7
    shodai is offline Senior Member
    Join Date
    Apr 2012
    Posts
    106
    Rep Power
    0

    Default Re: Array Troubles

    Quote Originally Posted by jim829 View Post
    The easiest way since you are familiar with the Scanner class for console input is to have the scanner instance read the file. Just look at the API for different Scanner constructors. There are several options to read files.

    Regards,
    Jim
    I get what the scanner instances are for, but I have to be totally honest that I have not a clue how to integrate it into this program. Can you help me to get the ball rolling?

  8. #8
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,377
    Rep Power
    5

    Default Re: Array Troubles

    First, have you ever used a scanner class to take input from a user and place the values into an array? Could you do that for this program. If so, then it is exactly the same way.

    You simply need to set up your scanner to read the file (see API). Then you need to iterate over the array elements and fill them in from the scanner method calls.

    Regards,
    Jim
    Last edited by jim829; 02-14-2014 at 07:50 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  9. #9
    shodai is offline Senior Member
    Join Date
    Apr 2012
    Posts
    106
    Rep Power
    0

    Default Re: Array Troubles

    I could read the entire file into the variable but it is the "tokenizer" that is confusing me. How do I break the file up and also collect it into the array?

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Array Troubles

    What is the layout of the data in the file? Are there records? How are the records separated? Is it possible to read one record at a time?

    Normal text files have records/lines that are separated by line-end characters. There are many methods that will read those records/lines like: readLine() or nextLine()
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Array Troubles

    There are many methods that will read those records/lines like: readLine() or nextLine()
    A BufferedReader has a readLine() method.

    A Scanner has a nextLine() method

    Java will take care of the line-endings whether they are Mac OS X or Unix (just a linefeed) or whether they are for Windows (a linefeed and a carriage-return) Java will just do the right thing.

  12. #12
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Array Troubles

    If you use a Scanner object, you pass it a File object -- not a filename as a String which won't work.

    Scanner fileScanner = new Scanner(new File("fileName.txt"));

    Something like the above line of code to create the Scanner object with "fileName.txt" being the file name that you want to read.

    Then for each line in the file, you could use a line of code such as the following:

    String line = fileScanner.nextLine();

    I believe that when there are no more lines to be read that line will be equal to null.

    Then to split up a line of text into fields, you could use the String split() method and split on commas, but you would have to be careful because there may be commas in the data, so it isn't really as easy as calling the split() method. For example there may be a field with an address such as the following:

    "city, state zip"

    The commas in this data can be challenging to work with.

    I'll leave it to you to try to put some code together and to post your code if you need more help.

    I would help more, but I don't want to be guilty of "spoon-feeding".

    "The Trouble With Spoon-Feeding"
    Java Programming Forums - The Java Community - The Problem with Spoon-feeding
    Last edited by kaydell2; 02-14-2014 at 07:54 PM.

  13. #13
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Array Troubles

    One challenge that you will face in reading in a CSV file into an array is that when you create the array, you have to know how many rows and columns that you will need and you won't know this until you read the data from the file.
    Nope! You can easily reallocate the arrays dynamically. See the Arrays class. At least one greater challenge is handling embedded commas within Strings which are separated values.
    My point is that in the Java language that when you create any array that you have to know the size and this size cannot be changed. This is a limitation of arrays in the Java language. Whether you use an ArrayList or allocate new arrays when an array is full, the following is true:

    1. You have to specify the size of any array when it is created.
    2. You cannot change the size of an array.
    A. You can't make it bigger
    B. You can't make is smaller.

    I suggested two possible solutions to this limitation of the Java language.

    1. Make two passes over the data
    A. One to find out how big of an array that you need
    B. Make a second pass to populate the arrays with data.

    You can't just say "Nope!" because this solution does work. You could say that you have a third solution. But even if you use the Arrays class, you can't change the size of an array in Java. You can create new arrays and copy over the data from the old arrays, but both of my proposed solutions do work.

    My second solution works too.

    2. You can use an ArrayList of ArrayLists and objects of the ArrayList class can grow and shrink. But deep down the ArrayList class uses Java arrays and when an array within an ArrayList object is full and you try to add another element, the code from the ArrayList class essentially does what is proposed in the third solution and that it new arrays are created and the data from the old arrays is copied into the new arrays.

    No matter which solution you use, the size of an array in Java is fixed at the size that it is created with.

    So, there are three solutions proposed now, all of which will work, but if this is becoming more confusing, you can use my first solution and make two passes over the data. 1. calculate the size of the arrays to be created, 2. Make a second pass over the data to populate the arrays with data.

    This will work. I've done it before.

    It's just inacurate for anybody to say "Nope!" to this solution.

  14. #14
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,377
    Rep Power
    5

    Default Re: Array Troubles

    Quote Originally Posted by kaydell2 View Post
    It's just inacurate for anybody to say "Nope!" to this solution.
    I didn't say nope to your solution. I said nope that you can't reallocate the arrays. The Arrays class does that. It provides a larger array with the values copied into it. And that's exactly what ArrayList does when it invokes ensureCapacity().

    But you did say the following which I didn't comment on.
    you have to know how many rows and columns that you will need
    That simply isn't true. You just make a guess and if it gets filled up you reallocate.

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

  15. #15
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Array Troubles

    you have to know how many rows and columns that you will need
    That simply isn't true. You just make a guess and if it gets filled up you reallocate.
    I can agree that you can reallocate arrays that are bigger and copy the elements of the full array into the new, bigger array.

    I said nope that you can't reallocate the arrays. The Arrays class does that.
    I'd like to make the point that you can reallocate any array by creating a new array, specifying its size and copying the elements from the old array into the new array.

    You don't have to use the ArrayList class as I suggested and you don't have to use the Arrays class as you have suggested. Any Java programmer can create a larger array and copy the elements from the old array into the new, larger array.

    One of my main points was that when you create an array, you have to specify a size and that size cannot change.

    I agree with you that you can allocate a new array that is bigger. I actually like your solution better than my first solution of doing two passes over the data, but I like my second solution of using ArrayLists, but I realize that many instructors won't let students use ArrayLists (and maybe not the Arrays class either) but first want students to learn how to use arrays first.

  16. #16
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,377
    Rep Power
    5

    Default Re: Array Troubles

    I actually like your solution better than my first solution of doing two passes over the data, but I like my second solution of using ArrayLists,
    Interesting, because I prefer the ArrayLists solution too. Mainly because the ArrayLists do all the nasty work of "growing" the array dynamically for you.


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

  17. #17
    shodai is offline Senior Member
    Join Date
    Apr 2012
    Posts
    106
    Rep Power
    0

    Default Re: Array Troubles

    Ok, so I feel like I am getting really close now but the output is something that I do not really understand. The output that I am getting is "20 7 [[Ljava.lang.String;@11ea681" with the 20 and the 7 changing for each output in the array. I do not really understand the output, so does this make sense to anyone else??

    Java Code:
      public void convertFile()
      {
        String convertFilePath = ("C:\\Users\\Brad\\Downloads\\FB1.csv");
        //Date,Open,High,Low,Close,Volume,Adj Close
        try
        {
          BufferedReader br = new BufferedReader(new FileReader(convertFilePath));
          StringTokenizer st = null;
          System.out.println("Your file is being converted. This may take several minutes.");
    
          while((convertFilePath = br.readLine()) != null)
          {
            newRowNumber++;
    
            st = new StringTokenizer(convertFilePath, ",");
    
            while(st.hasMoreTokens())
            {
              newColumnNumber++;
              myFBfile[newRowNumber][newColumnNumber] = st.nextToken();
              System.out.println (newRowNumber +" "+ newColumnNumber +" "+ myFBfile);
            }
            newColumnNumber = 0;
          }
        }       
        catch (FileNotFoundException e) 
        {
          System.out.println("Encountered critical error. Your file has not been converted");
        } 
        catch (IOException e) 
        {
          System.out.println("Encountered critical error. Your file has not been converted");
        }
        
      }

  18. #18
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Array Troubles

    Your code that you posted doesn't compile. Will you provide code that is a short, self-contained, correct, compileable example (SSCCE)?

    Short, Self Contained, Correct Example

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default Re: Array Troubles

    Is this the part you don't recognize: [[Ljava.lang.String;@11ea681
    That is the String returned by a 2 dim String array's toString() method.
    If you would like to have the contents of a 2 dim array formatted for printing use this method:
    java.util.Arrays.deepToString(theArrayName);
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    shodai is offline Senior Member
    Join Date
    Apr 2012
    Posts
    106
    Rep Power
    0

    Default Re: Array Troubles

    Ok. I am soooo close now. I believe that all of my methods are working except for the printArray method. It only seems to print the very last element of the array for some reason. This is my full updated code.

    Java Code:
    public class DataAnalyzer
    {
      public static void main (String[] args)
      {
        ReadFiles aReadFiles = new ReadFiles();
        aReadFiles.fileCheck();
        aReadFiles.findRows();
        aReadFiles.convertFile();
        aReadFiles.printArray();
      }
    }
    Java Code:
    import java.nio.file.*;
    import static java.nio.file.AccessMode.*;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    
    
    
    public class ReadFiles
    {
      public static int numberOfRows;
      public static int rowNumber = 0;
      public static int columnNumber = 0;
      public static int newRowNumber = 0;
      public static int newColumnNumber = 0;
      public String [][] myFBfile = new String [431][8];
      public int x;
      public int y;
    
      public void fileCheck()
      {
        Path filePath = Paths.get("C:\\Users\\Brad\\Downloads\\FB1.csv");
        System.out.println("Path is " + filePath.toString());
        
        try
        {
          filePath.getFileSystem().provider().checkAccess(filePath, READ, EXECUTE);
          System.out.println("File can be read and executed");
        }
        
        catch (IOException e)
        {
          System.out.println ("File cannot be used for this application");
        }
      }
      
      public void findRows()
      {
        String filePath = ("C:\\Users\\Brad\\Downloads\\FB1.csv");
        
        try
        {
          BufferedReader br = new BufferedReader(new FileReader(filePath));
          StringTokenizer st = null;
          System.out.println("Your file is being analysed. This may take several minutes.");
    
          while((filePath = br.readLine()) != null)
          {
            rowNumber++;
                    
            st = new StringTokenizer(filePath, ",");
            columnNumber = 0;
          }
        }
        
        catch (FileNotFoundException e)
        {
          System.out.println ("Number of rows for this file cannot be found");
        } 
        
        catch (IOException e) 
        {
          System.out.println ("Number of rows for this file cannot be found");
        }
            
        System.out.println("Total Rows: " + (rowNumber));
      }
      
      public void convertFile()
      {
        String convertFilePath = ("C:\\Users\\Brad\\Downloads\\FB1.csv");
        //Date,Open,High,Low,Close,Volume,Adj Close
        try
        {
          BufferedReader br = new BufferedReader(new FileReader(convertFilePath));
          StringTokenizer st = null;
          System.out.println("Your file is being converted. This may take several minutes.");
    
          while((convertFilePath = br.readLine()) != null)
          {
            newRowNumber++;
    
            st = new StringTokenizer(convertFilePath, ",");
    
            while(st.hasMoreTokens())
            {
              newColumnNumber++;
              myFBfile[newRowNumber][newColumnNumber] = st.nextToken();
              //System.out.println (newRowNumber +" "+ newColumnNumber +" "+ myFBfile[newRowNumber][newColumnNumber]);
            }
            newColumnNumber = 0;
          }
        }       
        catch (FileNotFoundException e) 
        {
          System.out.println("Encountered critical error. Your file has not been converted");
        } 
        catch (IOException e) 
        {
          System.out.println("Encountered critical error. Your file has not been converted");
        }
        
      }
      
      public void printArray()
      {
        for (x = 1; x < 20; x++);
        {
          for(y = 1; y < 7; y++);
          {
            System.out.println (x +" "+ y +" "+ myFBfile[x][y]);
          }
          y = 1;
        }
      }
    }

Page 1 of 2 12 LastLast

Similar Threads

  1. Array Troubles
    By shodai in forum New To Java
    Replies: 2
    Last Post: 02-11-2014, 05:43 PM
  2. HashMap Troubles
    By Cod in forum New To Java
    Replies: 5
    Last Post: 02-09-2014, 10:52 AM
  3. troubles with CardLayout
    By StaticFlow in forum AWT / Swing
    Replies: 3
    Last Post: 05-25-2012, 02:27 AM
  4. Integer troubles again...
    By Tb0h in forum New To Java
    Replies: 1
    Last Post: 09-20-2009, 02:32 AM
  5. [SOLVED] Array troubles, yes I searched...
    By Reiyn in forum New To Java
    Replies: 11
    Last Post: 04-16-2009, 11:28 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
  •