Java Collections interface and file output

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1202 Views - Last Post: 30 July 2009 - 12:26 AM Rate Topic: -----

#1 BCurley1973  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-July 09

Java Collections interface and file output

Posted 29 July 2009 - 11:14 PM

I am attempting to do an assignment for my Java programming class in which the application reads from an input file that contains book records with the following fields: first name, last name, ISBN Number, and publisher name. The application is supposed to output the publisher names without duplication. I can get the file to output the publisher's name, but it does not check for duplications, so there are multiple instances of the publisher's name, which is not the desired output.

This is my code for the BookRecord.java file:
public class BookRecord
{

	// Declare the variables that will be used in this class file
	private String firstName;
	private String lastName;
	private int ISBNNumber;
	private String publisherName;


	// Method that is used as a no-argument constructor to call other constructor
	// with default values
	public BookRecord()
	{
		// Calls four argument constructor using default values
		this( "", "", 0, "" );
	} // Ends no-argument constructor


	// Method used as a constructor to initialize a single record
	public BookRecord( String fName, String lName, int number, String publisher )
	{
		// Intitialize firstName variable
		setFirstName( fName );
		// Intitialize lastName variable
		setLastName( lName );
		// Initialize ISBNNumber variable
		setISBNNumber( number );
		// Initialize publisherName variable
		setPublisherName( publisher );
	} // Ends four-argument BookRecord constructor


	// Method used to set the first name
	public void setFirstName( String fName )
	{
		firstName = fName;
	} // Ends method setFirstName


	// Method used to get the first name
	public String getFirstName()
	{
		// Returns the first name
		return firstName;
	} // Ends method getFirstName


	public void setLastName( String lName )
	{
		lastName = lName;
	} // Ends method setLastName


	public String getLastName()
	{
		// Returns the last name
		return lastName;
	} // Ends method getLastName


	public void setISBNNumber( int number )
	{
		ISBNNumber = number;
	} // Ends method setISBNNumber


	public int getISBNNumber()
	{
		// Returns the ISBN number
		return ISBNNumber;
	} // Ends method getISBNNumber;


	public void setPublisherName( String publisher )
	{
		publisherName = publisher;
	} // Ends method setPublisherName


	public String getPublisherName()
	{
		// Returns the publisher name
		return publisherName;
	} // Ends method getPublisherName

} // Ends class file BookRecord




This is my code for the ProcessBookRecords.java file:
// Import statements used to get all needed information and commands
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IllegalFormatException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;

public class ProcessBookRecords
{

	// Declaration of variables
	// Declares an instance of the Scanner object
	private static Scanner inputBookRecord;
	// Declares an instance of the FileWriter object
	private static FileWriter outputPublisherList;
	// Declares an instance variable of the record that is being read
	private static BookRecord bookRecord;
	// Declares an instance of the ArrayList object
	private static ArrayList publisherList = new ArrayList();


	// Method used to open the text files used by the application
	public void openFiles()
	{
		// Try statement that opens the text files
		try
		{
			// Uses Scanner object to open and read from input BookRecords.txt file
			inputBookRecord = new Scanner( new File( "BookRecords.txt" ) );
			// Uses FileWriter object to open and write to output PublisherList.txt file
			outputPublisherList = new FileWriter( "PublisherList.txt", true );
		} // Ends try statement

		// Catch statement used when the file is not found
		catch( FileNotFoundException fileNotFoundException )
		{
			// Prints error message
			System.err.println( "The file was not found and could not be opened." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement used when the file cannot be accessed
		catch( SecurityException securityException )
		{
			// Prints error message
			System.err.println( "The file has restricted access and cannot be opened." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement used when there is an I/O error
		catch( IOException ioException )
		{
			// Prints error message
			Logger.getLogger( ProcessBookRecords.class.getName() ).log( Level.SEVERE, null, ioException );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method openFiles


	// Method used to read records from the input BookInformation.txt file
	public BookRecord getBookRecord()
	{
		// Places the record being read into the record object
		BookRecord record = new BookRecord();

		// If statement that checks for the next record and reads it if there is one
		if (inputBookRecord.hasNext() )
		{
			// Reads the first name
			record.setFirstName( inputBookRecord.next() );

			// Reads the last name
			record.setLastName( inputBookRecord.next() );

			// Reads the ISBN Number
			record.setISBNNumber( inputBookRecord.nextInt() );

			// Reads the publisher name
			record.setPublisherName( inputBookRecord.next() );
		} // Ends if statement

		// Else statement that sets record variable to null if there are no more records to read
		else
		{
			record = null;
		} // Ends else statement

		// Returns the record variable
		return record;

	} // Ends method BookRecord


	// Method used to determine if the publisher name has already been read
	public void processBookRecord()
	{
		// Reads the book record
		bookRecord = getBookRecord();

		// Try statement used to read records, create temporary record, and check publisher
		try
		{
			// While statement that ends when there are no more records to read
			while( bookRecord != null )
			{
				// If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )
				{
					// Creates a temporary record for the publisher name
					StringBuffer tempRecord = new StringBuffer();

					// Appends the publisher name to the temporary record
					tempRecord.append( bookRecord.getPublisherName() );

					// Appends an end of line marker to the temporary record
					tempRecord.append( System.getProperty( "line.separator" ) );

					// Outputs temporary record to PublisherList.txt file
					outputPublisherList.write( tempRecord.toString().toCharArray() );
				} // Ends if statement

				// Reads the next book record
				bookRecord = getBookRecord();
			} // Ends while statement
		} // Ends try statement

		// Catch statement for bad format
		catch( IllegalFormatException formatException )
		{
			// Prints error statement
			System.err.println( "There was an error with the output." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement for I/O errors
		catch( IOException ioException )
		{
			// Prints error statement
			System.err.println( "There was an error creating the file." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method processBookRecord


	// Method used to close text files
	public void closeFiles()
	{
		// Try statement used to close the files
		try
		{
			// If statement that closes BookRecords.txt file if it is not empty
			if( inputBookRecord != null )
			{
				inputBookRecord.close();
			} // Ends if statement

			// If statement that closes PublisherList.txt file if it is not empty
			if( outputPublisherList != null )
			{
				outputPublisherList.close();
			} // Ends if statement
		} // Ends try statement

		// Catch statement for I/O errors
		catch ( IOException ioException )
		{
			// Prints error message
			System.err.println( "There was an error closing the files." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method closeFiles

} // Ends class file ProcessBookRecords



And this is my code for the ProcessBookRecordsTest.java file:
public class ProcessBookRecordsTest
{

	/**
	 * @param args the command line arguments
	 */
	public static void main(String[] args)
	{
		// Creates an application that will run the program
		ProcessBookRecords application = new ProcessBookRecords();

		// Calls method used to open files
		application.openFiles();

		// Calls method used to process records
		application.processBookRecord();

		// Calls method used to close files
		application.closeFiles();
	} // Ends main method

} // Ends main class file ProcessBookRecordsTest



Is This A Good Question/Topic? 0
  • +

Replies To: Java Collections interface and file output

#2 syfran  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 83
  • View blog
  • Posts: 1,103
  • Joined: 12-July 09

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:24 PM

You could read it into a collection that cannot contain duplicates. A set will work for that.

This post has been edited by syfran: 29 July 2009 - 11:24 PM

Was This Post Helpful? 0
  • +
  • -

#3 BCurley1973  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-July 09

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:27 PM

View Postsyfran, on 29 Jul, 2009 - 10:24 PM, said:

You could read it into a collection that cannot contain duplicates. A set will work for that.

That is what I thought I did. Is this code not accurate?

 // If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )
				{
					// Creates a temporary record for the publisher name
					StringBuffer tempRecord = new StringBuffer();

					// Appends the publisher name to the temporary record
					tempRecord.append( bookRecord.getPublisherName() );

					// Appends an end of line marker to the temporary record
					tempRecord.append( System.getProperty( "line.separator" ) );

					// Outputs temporary record to PublisherList.txt file
					outputPublisherList.write( tempRecord.toString().toCharArray() );


Was This Post Helpful? 0
  • +
  • -

#4 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:33 PM

if you want to use ArrayLists then when you insert data into it, you can use the contains() method to check if the data is already there or not, then your ArrayList will have no duplicates and thus you'll be getting the correct output. hope this helps :)
Was This Post Helpful? 0
  • +
  • -

#5 syfran  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 83
  • View blog
  • Posts: 1,103
  • Joined: 12-July 09

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:41 PM

doesn't look like you ever add anything to publisherList and therefore your .contains() will not work.

Though it looks like you are checking duplicates I was referring to this as a set.

This post has been edited by syfran: 29 July 2009 - 11:43 PM

Was This Post Helpful? 0
  • +
  • -

#6 BCurley1973  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-July 09

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:42 PM

View Postmostyfriedman, on 29 Jul, 2009 - 10:33 PM, said:

if you want to use ArrayLists then when you insert data into it, you can use the contains() method to check if the data is already there or not, then your ArrayList will have no duplicates and thus you'll be getting the correct output. hope this helps :)



I tried that. It is in my code:

// If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )



I am still getting duplicates. Is it possibly just in the wrong place?
Was This Post Helpful? 0
  • +
  • -

#7 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:50 PM

View PostBCurley1973, on 29 Jul, 2009 - 10:42 PM, said:

View Postmostyfriedman, on 29 Jul, 2009 - 10:33 PM, said:

if you want to use ArrayLists then when you insert data into it, you can use the contains() method to check if the data is already there or not, then your ArrayList will have no duplicates and thus you'll be getting the correct output. hope this helps :)



I tried that. It is in my code:

// If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )



I am still getting duplicates. Is it possibly just in the wrong place?


oh sorry for that, didn't see that you already did that :)

can you post your class as one piece coz i dont know what goes where in your code
Was This Post Helpful? 0
  • +
  • -

#8 BCurley1973  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-July 09

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:54 PM

View Postmostyfriedman, on 29 Jul, 2009 - 10:50 PM, said:

View PostBCurley1973, on 29 Jul, 2009 - 10:42 PM, said:

View Postmostyfriedman, on 29 Jul, 2009 - 10:33 PM, said:

if you want to use ArrayLists then when you insert data into it, you can use the contains() method to check if the data is already there or not, then your ArrayList will have no duplicates and thus you'll be getting the correct output. hope this helps :)



I tried that. It is in my code:

// If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )



I am still getting duplicates. Is it possibly just in the wrong place?


oh sorry for that, didn't see that you already did that :)

can you post your class as one piece coz i dont know what goes where in your code


This is my code for the object file ProcessBookRecords.java file:

// Import statements used to get all needed information and commands
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IllegalFormatException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;

public class ProcessBookRecords
{

	// Declaration of variables
	// Declares an instance of the Scanner object
	private static Scanner inputBookRecord;
	// Declares an instance of the FileWriter object
	private static FileWriter outputPublisherList;
	// Declares an instance variable of the record that is being read
	private static BookRecord bookRecord;
	// Declares an instance of the ArrayList object
	private static ArrayList publisherList = new ArrayList();
	// Creates a set for the list of publishers
	private static Set publisherSet = new HashSet();


	// Method used to open the text files used by the application
	public void openFiles()
	{
		// Try statement that opens the text files
		try
		{
			// Uses Scanner object to open and read from input BookRecords.txt file
			inputBookRecord = new Scanner( new File( "BookRecords.txt" ) );
			// Uses FileWriter object to open and write to output PublisherList.txt file
			outputPublisherList = new FileWriter( "PublisherList.txt", true );
		} // Ends try statement

		// Catch statement used when the file is not found
		catch( FileNotFoundException fileNotFoundException )
		{
			// Prints error message
			System.err.println( "The file was not found and could not be opened." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement used when the file cannot be accessed
		catch( SecurityException securityException )
		{
			// Prints error message
			System.err.println( "The file has restricted access and cannot be opened." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement used when there is an I/O error
		catch( IOException ioException )
		{
			// Prints error message
			Logger.getLogger( ProcessBookRecords.class.getName() ).log( Level.SEVERE, null, ioException );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method openFiles


	// Method used to read records from the input BookInformation.txt file
	public BookRecord getBookRecord()
	{
		// Places the record being read into the record object
		BookRecord record = new BookRecord();

		// If statement that checks for the next record and reads it if there is one
		if (inputBookRecord.hasNext() )
		{
			// Reads the first name
			record.setFirstName( inputBookRecord.next() );

			// Reads the last name
			record.setLastName( inputBookRecord.next() );

			// Reads the ISBN Number
			record.setISBNNumber( inputBookRecord.nextInt() );

			// Reads the publisher name
			record.setPublisherName( inputBookRecord.next() );
		} // Ends if statement

		// Else statement that sets record variable to null if there are no more records to read
		else
		{
			record = null;
		} // Ends else statement

		// Returns the record variable
		return record;

	} // Ends method BookRecord


	// Method used to determine if the publisher name has already been read
	public void processBookRecord()
	{
		// Reads the book record
		bookRecord = getBookRecord();

		// Try statement used to read records, create temporary record, and check publisher
		try
		{
			// While statement that ends when there are no more records to read
			while( bookRecord != null )
			{
				// If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )
				{
					// Creates a temporary record for the publisher name
					StringBuffer tempRecord = new StringBuffer();

					// Appends the publisher name to the temporary record
					tempRecord.append( bookRecord.getPublisherName() );

					// Appends an end of line marker to the temporary record
					tempRecord.append( System.getProperty( "line.separator" ) );

					// Outputs temporary record to PublisherList.txt file
					outputPublisherList.write( tempRecord.toString().toCharArray() );
				} // Ends if statement

				// Reads the next book record
				bookRecord = getBookRecord();
			} // Ends while statement
		} // Ends try statement

		// Catch statement for bad format
		catch( IllegalFormatException formatException )
		{
			// Prints error statement
			System.err.println( "There was an error with the output." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement for I/O errors
		catch( IOException ioException )
		{
			// Prints error statement
			System.err.println( "There was an error creating the file." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method processBookRecord


	// Method used to close text files
	public void closeFiles()
	{
		// Try statement used to close the files
		try
		{
			// If statement that closes BookRecords.txt file if it is not empty
			if( inputBookRecord != null )
			{
				inputBookRecord.close();
			} // Ends if statement

			// If statement that closes PublisherList.txt file if it is not empty
			if( outputPublisherList != null )
			{
				outputPublisherList.close();
			} // Ends if statement
		} // Ends try statement

		// Catch statement for I/O errors
		catch ( IOException ioException )
		{
			// Prints error message
			System.err.println( "There was an error closing the files." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method closeFiles

} // Ends class file ProcessBookRecords



Was This Post Helpful? 0
  • +
  • -

#9 syfran  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 83
  • View blog
  • Posts: 1,103
  • Joined: 12-July 09

Re: Java Collections interface and file output

Posted 29 July 2009 - 11:57 PM

I ask again, do you add anything to the publisherList?
Was This Post Helpful? 0
  • +
  • -

#10 BCurley1973  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-July 09

Re: Java Collections interface and file output

Posted 30 July 2009 - 12:03 AM

View Postsyfran, on 29 Jul, 2009 - 10:57 PM, said:

I ask again, do you add anything to the publisherList?


I thought I did. how do I make sure?
Was This Post Helpful? 0
  • +
  • -

#11 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: Java Collections interface and file output

Posted 30 July 2009 - 12:06 AM

no, he's not inserting anything in the publisherList
Was This Post Helpful? 0
  • +
  • -

#12 syfran  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 83
  • View blog
  • Posts: 1,103
  • Joined: 12-July 09

Re: Java Collections interface and file output

Posted 30 July 2009 - 12:07 AM

You'd be looking for a publisherList.add() in that class, which I can't find.

 // If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )
				{
					  publisherList.add(bookRecord.getPublisherName());


That should get what you need.

This post has been edited by syfran: 30 July 2009 - 12:08 AM

Was This Post Helpful? 0
  • +
  • -

#13 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: Java Collections interface and file output

Posted 30 July 2009 - 12:10 AM

that's it actually, you're not inserting anything in the publisherList, so each time you check if its there or not, it will surely be not there even if you already inputted that info before..so you will be getting duplicates in your output

try adding this
 public void processBookRecord()
	{
		// Reads the book record
		bookRecord = getBookRecord();

		// Try statement used to read records, create temporary record, and check publisher
		try
		{
			// While statement that ends when there are no more records to read
			while( bookRecord != null )
			{
				// If statement to check if publisher name has previously been read
				if( !publisherList.contains( bookRecord.getPublisherName() ) )
				{
					// Creates a temporary record for the publisher name
					publisherList.add(bookRecord.getPublisherName());

					StringBuffer tempRecord = new StringBuffer();

					// Appends the publisher name to the temporary record
					tempRecord.append( bookRecord.getPublisherName() );

					// Appends an end of line marker to the temporary record
					tempRecord.append( System.getProperty( "line.separator" ) );

					// Outputs temporary record to PublisherList.txt file
					outputPublisherList.write( tempRecord.toString().toCharArray() );
				} // Ends if statement

				// Reads the next book record
				bookRecord = getBookRecord();
			} // Ends while statement
		} // Ends try statement

		// Catch statement for bad format
		catch( IllegalFormatException formatException )
		{
			// Prints error statement
			System.err.println( "There was an error with the output." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement

		// Catch statement for I/O errors
		catch( IOException ioException )
		{
			// Prints error statement
			System.err.println( "There was an error creating the file." );
			// Exits the program
			System.exit( 1 );
		} // Ends catch statement
	} // Ends method processBookRecord


Was This Post Helpful? 0
  • +
  • -

#14 BCurley1973  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-July 09

Re: Java Collections interface and file output

Posted 30 July 2009 - 12:16 AM

Thanks to the both of you. Now it works perfectly. I knew it was probably a simple issue. You both helped a lot!
Was This Post Helpful? 0
  • +
  • -

#15 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: Java Collections interface and file output

Posted 30 July 2009 - 12:24 AM

no problem :)..a small suggestion though , you don't really have to comment every single line in your code..lots of lines there man..they can scramble your brain :P
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2