Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Having an issue reading files to create two arrays.

  1. #1
    Junior Member
    Join Date
    Jul 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Having an issue reading files to create two arrays.

    This project is a Library Lending System, and I am having issues getting the information concerning the borrowers and items to be entered by reading some text files where the fields are separated by commas. I know I need to use the FileReader and BuffereReader classes, but I can't figure out where to put the information. The portion of the code that starts creating the borrowers is about 20 lines down. Any help would be greatly appreciated.

    Thanks.


    /
    /Imports the classes necessary to run the Controller class.
    import java.awt.ItemSelectable;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import javax.swing.JOptionPane;
     
    //Controller class connects the librarian to the rest of the program.
    public class Controller
    {
    //Creates Hashmaps for contents and borrowers.
        private HashMap <String,Item> contents = new HashMap <String,Item> ();
        private HashMap <String,Borrower> borrowers = new HashMap <String, Borrower> ();
     
    // Controller Constructor.
        Controller()
        {
     
    //Declares Instances.
            Book book;
    	Music music;
     
    //Creates borrower accounts.
    	Borrower b = new Borrower();
    	b.setID("001");
    	b.setName("D. Manson");
    	borrowers.put(b.getID(),b);
     
    	b = new Borrower();
    	b.setID("002");
    	b.setName("V. Tran");
    	borrowers.put(b.getID(),b);
     
    	b = new Borrower();
    	b.setID("003");
    	b.setName("A. Dumas");
    	borrowers.put(b.getID(),b);
     
    		// Initialize catalog records
    		book = new Book();
    		book.setCode("HPDH");
    		book.setTitle("Harry Potter and the Deathly Hallows");
    		book.setAuthor("J.K.Rowling");
    		book.setSubject("Wizarding");
    		book.setPages("759");
    		book.setQuantity(3);
    		book.setImgURL("./images/hpdh.jpg");
    		contents.put(book.getCode(),book);
     
    		book = new Book();
    		book.setCode("CSH");
    		book.setTitle("The Complete Sherlock Holmes");
    		book.setAuthor("Sir Arthur Conan Doyle");
    		book.setSubject("Who Done It");
    		book.setPages("1122");
    		book.setQuantity(2);
    		book.setImgURL("./images/sherlock.jpg");
    		contents.put(book.getCode(),book);
     
    		book = new Book();
    		book.setCode("PL");
    		book.setTitle("Pirate Latitudes");
    		book.setAuthor("Michael Crichton");
    		book.setSubject("Adventure");
    		book.setPages("312");
    		book.setQuantity(1);
    		book.setImgURL("./images/pirate.jpg");
    		contents.put(book.getCode(),book);
     
    		music = new Music();
    		music.setCode("HWGA");
    		music.setTitle("Here We Go Again");
    		music.setArtist("Wynton Marsalis");
    		music.setGenre("Blues");
    		music.setFormat("Audio CD");
    		music.setQuantity(3);
    		music.setImgURL("./images/marsalis.jpg");
    		contents.put(music.getCode(), music);
     
    		music = new Music();
    		music.setCode("MC");
    		music.setTitle("McCartney");
    		music.setArtist("Paul McCartney");
    		music.setGenre("Rock");
    		music.setFormat("MP3 Download");
    		music.setQuantity(2);
    		music.setImgURL("./images/mccartney.jpg");
    		contents.put(music.getCode(), music);
     
    		music = new Music();
    		music.setCode("G");
    		music.setTitle("Guilt");
    		music.setArtist("Nero");
    		music.setGenre("Dubstep");
    		music.setFormat("MP3 Download");
    		music.setQuantity(4);
    		music.setImgURL("./images/nero.jpg");
    		contents.put(music.getCode(), music);
     
    		music = new Music();
    		music.setCode("S");
    		music.setTitle("Strobe");
    		music.setArtist("Deadmau5");
    		music.setGenre("House");
    		music.setFormat("MP3 Download");
    		music.setQuantity(1);
    		music.setImgURL("./images/deadmau5.jpg");
    		contents.put(music.getCode(), music);
     
    		music = new Music();
    		music.setCode("GT");
    		music.setTitle("Group Therapy");
    		music.setArtist("Above and Beyond");
    		music.setGenre("Trance");
    		music.setFormat("Audio CD");
    		music.setQuantity(2);
    		music.setImgURL("./images/grouptherapy.jpg");
    		contents.put(music.getCode(), music);
    	}
     
    //Sorts the catalog items alphabetically.
        String getCatalog()
        {
     
    //Sorts items by key values.
        Vector <String> v = new Vector <String> (contents.keySet());
        Collections.sort(v);
     
    // Returns the sorted results.
        Item myItem;
        String msg = "";
        for (Enumeration <String> e = v.elements(); e.hasMoreElements();)
            {
    	String ID = (String) e.nextElement();
    	myItem = contents.get(ID);
    	msg += myItem.examine() + "\n \n";
    	}
    	return msg;
        }
     
    //Checks out an item.
        void checkout(String borrowerID, String itemIDIn, String itemID,
        String copyID, String dateOut, String dateDue)
        {
            try
    	{
    //Lookup borrower, lookup item, add borrower to copy of item, and update borrower's record
                Borrower borrower;
                Item item;
                borrower = borrowers.get(borrowerID);
                item = contents.get(itemID);
                item.addBorrower(copyID, borrowerID);
                borrower.addItemOut(itemIDIn, dateOut, dateDue);
     
    //Update item count by subtracting 1 from the existing quantity.
                contents.get(itemID).quantity--;
    	}
    	catch (Exception e)
    	{
    	JOptionPane.showMessageDialog(null,"HI","CPP Library "
            + "Lending System", JOptionPane.INFORMATION_MESSAGE);
    	}
        }
     
    //Returns an item.
        void checkIn(String itemIDIn, String itemID, String copyID, String dateIn)
        {
            try
    	{
    //Lookups item, find out who borrowed it, and update borrower's record
                Borrower borrower;
                Item item;
                item = contents.get(itemID);
                borrower = borrowers.get(item.getBorrowerID(copyID));
                borrower.addItemIn(itemIDIn, dateIn);
     
    //Update item count by adding 1 to the existing quantity.
                contents.get(itemID).quantity++;
    	}
    	catch(Exception e)
    	{
                JOptionPane.showMessageDialog(null,"Unable to process request",
    	    "CPP Library Lending System", JOptionPane.INFORMATION_MESSAGE);
    	}
        }
     
     
    //Returns the borrower's history.
        String getBorrowerHistory(String anID)
        {
            try
            {
                return borrowers.get(anID).getHistory();
            }
            catch (Exception e)
    	{
                return "";
    	}
        }
     
    //Returns the Image associated with the item.
        String getImgURL(String itemID)
        {
            String item = contents.get(itemID).getImgURL();
    	return item;
        }
     
    //Checks if the item has a quantity above 0.
        boolean isItemAvailable(String itemID)
        {
            Item item = contents.get(itemID);
    	boolean result;
    	if (item.quantity > 0)
    	result = true;
    	else
    	result = false;
    	return result;
        }
     
    //Checks if the borrower is valid.
        boolean isValidBorrower(String anID)
        {
            return borrowers.containsKey(anID);
        }
     
    //Checks if item is in the catalog.
        boolean isValidItem(String itemID)
        {
            return contents.containsKey(itemID);
        }
    //Checks if the date is in a valid format.
        boolean isValidDate (String aDate)
        {
    	boolean result = false;
    	SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
    	sdf.setLenient(false);
    	try
    	{
                sdf.parse(aDate);
                return true;
    	}
    	catch(Exception e)
    	{
            }
     
    	return result;
        }
     
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,421
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Having an issue reading files to create two arrays.

    I am having issues getting the information concerning the borrowers and items to be entered by reading some text files
    Looks like you have posted more code than you need for working on reading a file into an array.
    Where are you using the file reading classes and methods? I don't see them.

    I suggest that you write a small, simple program that reads the file, parses the fields in each record and just prints them out for now. When you get the techniques on how to read a file, etc, then work on merging that logic into the larger program.

  3. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Having an issue reading files to create two arrays.

    Your post is vague and along the lines of "Here's my code, it doesn't work, fix it". That is not how it works. You need to identify what your problem is and ask a specific question. The more specific it is, the more specific the answer you get will be.

    If you have data in a file which I presume will represent a book, then you need to have a Book class. Then you can read the file (line by line), break down the information (you said it is comma separated), create a Book object from the data and store that object into a Collection suck as a List. Repeat this until the file has been completely read.
    Improving the world one idiot at a time!

  4. #4
    Junior Member
    Join Date
    Jul 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Having an issue reading files to create two arrays.

    Ok, how is this then. I am reading the Music file that I mentioned in my previous post using the code listed below. The format that I get back is what I am initially looking for:
    TH-2,Thriller,Michael Jackson,Rock,MP3 Download,1

    My ultimate goal is to parse this data by separating it into different strings by using the commas as a delimiter and then put that information into an array.


    import java.io.*;
    import java.util.Scanner;
     
    public class FileInput {
     
      public static void main(String[] args) {
     
        File file = new File("c:/files/Borrowers.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
     
        try {
          fis = new FileInputStream(file);
     
          // Here BufferedInputStream is added for fast reading.
          bis = new BufferedInputStream(fis);
          dis = new DataInputStream(bis);
     
          // dis.available() returns 0 if the file does not have more lines.
          while (dis.available() != 0) {
     
          // this statement reads the line from the file and print it to
            // the console.
            System.out.println(dis.readLine());
          }
     
          // dispose all the resources after using them.
          fis.close();
          bis.close();
          dis.close();
     
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
     
      }
     
    }

  5. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Having an issue reading files to create two arrays.

    Quote Originally Posted by ccrosby View Post
    My ultimate goal is to parse this data by separating it into different strings by using the commas as a delimiter and then put that information into an array.
    Sounds lika a plan. Do you have a question about that? Nudge: check out the methods in the String class.
    Improving the world one idiot at a time!

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,421
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Having an issue reading files to create two arrays.

    To work out the next bit of code, you won't need a file. again a small program that Puts a typical line from your file in a String for trying to split it into separate words.

Similar Threads

  1. How to create or edit .ser files in Jar files
    By xbill in forum Java IDEs
    Replies: 1
    Last Post: May 18th, 2011, 05:15 AM
  2. Issue with setting up different class with arrays
    By D-COD3R in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 4th, 2011, 06:09 PM
  3. issue with reading a clob variable from oracle
    By computerbum in forum What's Wrong With My Code?
    Replies: 2
    Last Post: August 28th, 2010, 06:08 PM
  4. Reading CSV files into a program
    By Wrathgarr in forum Java Theory & Questions
    Replies: 2
    Last Post: April 15th, 2010, 10:41 AM
  5. Reading many files using a scanner
    By jayjames90 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: October 22nd, 2009, 04:35 PM