Results 1 to 17 of 17
  1. #1
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Parsing a CSV File and storing it into an ArrayList

    Java Code:
    package inventory;
    
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    
    public class Inventory 
    {   
        private static Scanner scan = new Scanner(System.in);
        
        public static void main(String[] args)
        {
            ArrayList<Product> InventoryList = new ArrayList<>();
            Inventory I = new Inventory();
            int option = 0;
            
            Inventory.openFile(InventoryList);
            
            while(option != 4)
            {
                System.out.println("1.) Add items to the inventory");
                System.out.println("2.) Show items in the inventory");
                System.out.println("3.) Show the total cost of the inventory.");
                System.out.println("4.) Quit the program.");
                option = scan.nextInt();
                
                switch(option)
                {
                    case 1:
                        I.addItems(InventoryList);
                        break;
                    case 2:
                        I.showInventory(InventoryList);
                        break;
                    case 3:
                        I.showTotalCost(InventoryList);
                        break;
                    case 4:
                        System.out.println("\nApplication Terminated.");
                        break;
                    default:
                        System.out.println("This option does not exist in the menu. Try again");
                        break;
                }
            }
        }
        
        public static void openFile(ArrayList<Product> p)
        {   
           Scanner scan = null;
           String firstLine = "";
           String line;
           
         try
         {
           scan = new Scanner(new FileReader("product.csv"));
           
           firstLine = scan.nextLine();
           
           while(scan.hasNextLine())
           {
               line = scan.nextLine();
               String[] items = line.split(",");
               
               Product product = new Product();
               
               product.setProductName(items[0]);
               product.setQuantity(Integer.parseInt(items[1]));
               product.setPrice(Double.parseDouble(items[2]));
               product.setUPC(items[3]);
               
               p.add(product);
           }
           scan.close();
         }
         catch(FileNotFoundException e)
         {
             System.err.println("File was not found");
         }
        }
        
        public static void writeFile(ArrayList<Product> p)
        {
            // This is where I am now
        }
        
        public void addItems(ArrayList<Product> p)
        {
            String productName;
            int quantity;
            double price;
            String UPC;
            
            scan.nextLine();
            
            System.out.println("\nEnter the name of the product?");
            productName = scan.nextLine();
            
            System.out.println("\nHow many of these items do you have?");
            quantity = scan.nextInt();
            
            System.out.println("\nWhat is the price of this item?");
            price = scan.nextDouble();
            
            scan.nextLine();
            
            System.out.println("\nWhat is the UPC number for this item?");
            UPC = scan.nextLine();
            
            if(p.size() > 0)
             {
                 for (Product pro : p) 
                 {
                     while(pro.getUPC().equals(UPC)) 
                     {
                         System.out.println("\nNo duplicates allowed, try again.");
                         UPC = scan.nextLine();
                     }
                 }
             }
            
            Product product = new Product(productName, quantity, price, UPC);
            
            p.add(product);
            
            System.out.println("");
        }
        
        public void showInventory(ArrayList<Product> p)
        {
           int choice;
           String response;
           Inventory I = new Inventory();
           
           System.out.println("");
           
           System.out.println("1.) Search the inventory by row");
           System.out.println("2.) Search the entire inventory");
           System.out.println("3.) Search the inventory by UPC ID");
           System.out.println("4.) Search the inventory by name");
           choice = scan.nextInt();
           scan.nextLine();
           
               if(choice == 1)
               {
                   int arrayLimit = p.size();
                   int row;
                   
                   System.out.println("\nEnter the row that you would like to search");
                   row = scan.nextInt();
                   
                   while(row > arrayLimit || row <= 0)
                   {
                       System.out.println("\nSorry, that row doesn't exist. Try again");
                       row = scan.nextInt();
                   }
                   
                   System.out.print("\nItem found: ");
                   
                   System.out.println(p.get(row-1));
                   
                   scan.nextLine();
                   
                   System.out.println("\nIs there another item that you would like to seacrh by row? ");
                   response = scan.nextLine();
                   
                   while(!(response.equalsIgnoreCase("Yes")) && !(response.equalsIgnoreCase("No")))
                   {
                       System.out.println("\nOnly, Yes or No are acceptable inputs. Try again.");
                       response = scan.nextLine();
                   }
                   
                   if(response.equalsIgnoreCase("Yes"))
                   {
                       System.out.println("\nStarting a new search");
                       I.showInventory(p);
                   }
                   else if(response.equalsIgnoreCase("No"))
                   {
                       System.out.println("\nReturning to the main menu\n");
                   }
               }
               else if(choice == 2)
               {
                   System.out.println("");
                   
                   for (Product p1 : p) 
                   {
                       System.out.println(p1);
                   }
                   
                   System.out.println("");
               }
               else if(choice == 3)
               {
                   String UPC;
                   
                   System.out.println("\nEnter the UPC serial number.");
                   UPC = scan.nextLine();
                   
                   System.out.print("\nItem found: ");
                   
               for (Product p1 : p) 
               {
                   if (p1.getUPC().equals(UPC)) 
                   {
                       System.out.println(p1);
                   }
                }
                   
                   System.out.println("\nIs there another item that you would like to search by UPC? ");
                   response = scan.nextLine();
                   
                   while(!(response.equalsIgnoreCase("Yes")) && !(response.equalsIgnoreCase("No")))
                   {
                       System.out.println("\nOnly, Yes or No are acceptable inputs. Try again.");
                       response = scan.nextLine();
                   }
                   
                   if(response.equalsIgnoreCase("Yes"))
                   {
                       System.out.println("\nStarting a new search");
                       I.showInventory(p);
                   }
                   else if(response.equalsIgnoreCase("No"))
                   {
                       System.out.println("\nReturning to the main menu\n");
                   }
               }
               else if(choice == 4)
               {
                   String productName;
                   
                   System.out.println("\nEnter the Name of the product.");
                   productName= scan.nextLine();
                   
                   for(int i=0; ; i++)
                   {
                       if (p.get(i).getProductName().equalsIgnoreCase(productName)) 
                        {
                             System.out.print("\nItem found: ");
                             System.out.println(p.get(i));
                             break;
                        }
                        else if(i == p.size()-1)
                        {
                            System.out.println("\nThis product is not in our inventory.");
                            break;
                        }
                   }
                   
                   System.out.println("\nIs there another item that you would like to search by Name? ");
                   response = scan.nextLine();
                   
                   while(!(response.equalsIgnoreCase("Yes")) && !(response.equalsIgnoreCase("No")))
                   {
                       System.out.println("\nOnly, Yes or No are acceptable inputs. Try again.");
                       response = scan.nextLine();
                   }
                   
                   if(response.equalsIgnoreCase("Yes"))
                   {
                       System.out.println("\nStarting a new search");
                       I.showInventory(p);
                   }
                   else if(response.equalsIgnoreCase("No"))
                   {
                       System.out.println("\nReturning to the main menu\n");
                   }
               }
        }
        
        public void showTotalCost(ArrayList<Product> p)
        {
            double totalCost = 0;
            
            for(int i=0; i<p.size(); i++)
            {
                totalCost += p.get(i).getPrice() * p.get(i).getQuantity();
            }
            
            System.out.println("");
            System.out.printf("The total cost of the entire inventory is %.2f",totalCost);
            System.out.println("\n");
        }
    }
    data from the file:
    Description Quantity Price UPC
    Sony Headphones 15 3.99 123456
    Motorola Tablet 55 499 987654
    HDMI Cables 101 16.99 789456
    Last edited by Deathslice; 03-02-2015 at 02:07 AM.

  2. #2
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    I was able to figure what I needed to do for the most part(look at the main post). Does it look like I need to add anything more? Maybe a check exception that I'm missing or something?
    Last edited by Deathslice; 03-01-2015 at 06:21 PM.

  3. #3
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Alright guys, now I'm in another predicament. What I would like to do is to update my file every time I add or remove objects from the Inventory(The code is suppose to go in the writeFile method). I know how to do it with an array of strings by invoking the write method from the bufferedWriter class but sadly, it doesn't have method for objects. What can I do?

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Quote Originally Posted by Deathslice View Post
    Alright guys, now I'm in another predicament. What I would like to do is to update my file every time I add or remove objects from the Inventory(The code is suppose to go in the writeFile method). I know how to do it with an array of strings by invoking the write method from the bufferedWriter class but sadly, it doesn't have method for objects. What can I do?
    Short of serialization, you need to provide methods in your object to read and write the data. Since the data is comprised of types that are supported by bufferedWriter, you simply employ them in your class to write those types. If your class has other objects, then you repeat the process. If you want to write objects of classes you don't own, then write sufficient data so you can recreate them when you read in data. Read about Serializable Objects (The Java™ Tutorials > Java Naming and Directory Interface > Java Objects in the Directory) to get a feel for how this works. That is essentially what you are doing anyway.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Hey jim, I serialize my product class and created a method called writeToFile. It looks like this.

    Java Code:
    public static void writeToFile(ArrayList<Product> p)
        {
            try 
            {
                BufferedWriter writer = new BufferedWriter(new FileWriter("product.csv"));
                
                for (Product p1 : p) 
                {
                    writer.write(p1.toString());
                }
                
                writer.close();
            } 
            catch (IOException ex) 
            {
                System.out.println("Input/Output format error");
            }
        }
    However there is a problem.

    This is how the file looks like before

    Description,Quantity,Price,UPC
    Sony Headphones,15,3.99,123456
    Motorola Tablet,55,499,987654
    HDMI Cables,101,16.99,789456


    and this is how looks after I use this method.

    Sony Headphones, 15, 3.99, 123456Motorola Tablet, 55, 499.0, 987654HDMI Cables, 101, 16.99, 789456Name, 5, 10.0, 2345678

    The names are gone(Description, quantity, price etc) and the format doesn't look like the one above. Even though the information was written to the file(as you can tell by this--> Name, 5, 10.0, 2345678), when I went to try to view the inventory while the program was running, the program says that there are no products when there are clearly 4 objects in the arrayList. What can I do? Could it be that I'm not serializing the arraylist properly?

    Note that I'm adding a new object and to the arrayList and thus new data to the file. Would the process be the same if just edit the preexisting objects(The sony headphones. tablet, and cables)?
    Last edited by Deathslice; 03-02-2015 at 05:02 PM.

  6. #6
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    I actually found an answer that kept the format but not the names because in the openFile method I skip that line. This of course causes a NumberFormatexception error because the sony headphone is now the one being skipped which of course is not good.

    Here are the two methods side by side

    Java Code:
    public static void openFile(ArrayList<Product> p)
        {   
           Scanner read;
           String firstLine = "";
           String line;
           
         try
         {
           read = new Scanner(new FileReader("product.csv"));
           
           firstLine = read.nextLine();// Skips the names
           
           while(read.hasNextLine())
           {
               line = read.nextLine();
               String[] items = line.split(",");
               
               Product product = new Product();
               
               product.setProductName(items[0]);
               product.setQuantity(Integer.parseInt(items[1]));
               product.setPrice(Double.parseDouble(items[2]));
               product.setUPC(items[3]);
               
               p.add(product);
           }
           read.close();
         }
         catch(FileNotFoundException e)
         {
             System.out.println("File was not found");
         }
        }

    Java Code:
     public static void writeToFile(ArrayList<Product> p)
        {
            try 
            {
                 PrintWriter pw = new PrintWriter(new FileWriter("product.csv"));
                
                for (Product pro : p)
                {
                   pw.println(pro);
                }
                
                pw.close();
            } 
            catch (IOException ex) 
            {
                System.out.println("Input/Output format error");
            }
        }
    I'm so close. All I need to do is fix this error. My fix is to just include the names in the arrayList if there is no work around.

    Also explain to me why the printwriter worked but not the bufferedWriter?
    Last edited by Deathslice; 03-02-2015 at 05:17 PM.

  7. #7
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Well I've been thinking about a way to solve this and this is what I came up with. How about when I call the writeToFile every time I add, edit, or remove an object, this method also skips the first line and the sony headphones will start at line number 2 instead of number 1(Note that at this point the has file has not been updated and the names are still there). This make sense because the names are always going to be at line 1. Would this work?

  8. #8
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Anybody has any ideas?

  9. #9
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    I thought of the short term solution by using a variable called int counterLine and increment it when it skips the line. This if statement will only work one time simply because I only need to skip the line one time. This didn't not work and I still got an Exception in thread "main" java.lang.NumberFormatException: For input string: " 55"(this is quantity for the motorola tablet) when I tried to run the program again(to see if the changes stay and work)

  10. #10
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    After pondering, i realized after while that my short term solution will never work.

  11. #11
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    This is interesting, If I output the string line variable when I invoke the openFile method for the first time, it outputs this
    Sony Headphones,15,3.99,123456
    Motorola Tablet,55,499,987654
    HDMI Cables,101,16.99,789456

    when I add new data to the file, terminate the program and then run the program again, the string variable outputs just this
    Motorola Tablet,55,499,987654

    Not all four objects(granted one of them is getting skip because I don't know a way to stop the method from doing that. So it's actually 3 objects it should output for the time being).

    This is just huge a mess. I need help at this point.

  12. #12
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Omg I can't believe I figured it out. It was all in the way it was formatted. Instead of "55" it was " 55" with the space character. All I had to do was change my toString method and it parsed it correctly. I don't suppose I could've used the trim method to eliminate the space character?
    Last edited by Deathslice; 03-02-2015 at 07:58 PM.

  13. #13
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Now that this problem is solved, I still have the problem of the function openFile skipping the first line. How would I go about fixing that?

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Parsing a CSV File and storing it into an ArrayList

    the problem of the function openFile skipping the first line.
    Can you explain what the problem is?
    What's done with the first line that the program reads?
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Here is the entire scenario with the problem of course. The first time the program runs it calls the openFile method to parse the csv file. It skips the first line(this part is intentional), because it contains data that I don't need. Now, the file that I have is preexisting data like this

    Description,Quantity,Price,UPC
    Sony Headphones,15,3.99,123456
    Motorola Tablet,55,499,987654
    HDMI Cables,101,16.99,789456

    Let say I enter 1 new data(or object because it's been updated by an arrayList that gets written to by the writeToFile method), like Name,5,10.00,546321(Note that it has same format in order to avoid a NumberFormat Exception). The file will then look like this

    Sony Headphones,15,3.99,123456
    Motorola Tablet,55,499,987654
    HDMI Cables,101,16.99,789456
    Name,5,10.00,546321

    I terminate the program and the file is saved.

    Cool, everything is going great. Here is the problem, When I run the program it will call the method openFile and the skip the first line again, omitting everything from the first row. Now when I run the writeToFile method again, that will not be there.

    This is my scenario.

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Parsing a CSV File and storing it into an ArrayList

    he method openFile and the skip the first line again,
    What does the code do with the contents of firstLine? Does that have the skipped line?
    If you don't understand my response, don't ignore it, ask a question.

  17. #17
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Parsing a CSV File and storing it into an ArrayList

    Quote Originally Posted by Deathslice View Post
    Omg I can't believe I figured it out. It was all in the way it was formatted. Instead of "55" it was " 55" with the space character. All I had to do was change my toString method and it parsed it correctly. I don't suppose I could've used the trim method to eliminate the space character?
    The answer is of course yes. I make it a rule of thumb to call trim() on data which is parsed from a stream and then converted to another datatype. It can't hurt.

    Of course that opens the door to a major pitfall that novices fall into easily, and that is to forget that String is immutable. I'm going to respectfully assume you do know what that means.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Storing object with int values in Arraylist.
    By Zigster in forum New To Java
    Replies: 12
    Last Post: 05-26-2012, 09:49 PM
  2. Replies: 2
    Last Post: 11-06-2011, 07:19 PM
  3. Replies: 2
    Last Post: 10-28-2010, 02:33 PM
  4. Storing data from text file in ArrayList
    By tjhodge in forum New To Java
    Replies: 1
    Last Post: 02-12-2009, 01:22 PM
  5. parsing/storing large text data
    By hkansal in forum New To Java
    Replies: 4
    Last Post: 10-19-2008, 06:34 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
  •