JAVA Collections (tree set)

  • Comp Sci
  • Thread starter iamjon.smith
  • Start date
  • #1
117
3
You have been tasked to develop an application that reads customer information from a file to determine in which states you have customers.

The file contains records with customer first name, customer last name, street address, city, and state.

The file could contain many customers living in the same state. You need to read all of the records from the file and store only the state information into a data structure without duplicates. The states need to be sorted alphabetically.

Main Class:
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);

       try{

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())
            { //Checks if there's any more lines

                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                State = scanner.next(); // reads to end of line sets the State

             }

            }

        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
           System.err.println ("Error writing to file");
        }
    }
  }

and my CustRecord Class:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jon and Jessica
 */


public class CustRecord {

   private String custFirst;
   private String custLast;
   private int streetNum;
   private String streetName;
   private String streetType;
   private String City;
   private String State;

   // no-argument constructor calls other constructor with default values
   public CustRecord()
   {
      this(  "", "", 0, "","", "","" ); // call six-argument constructor
   } // end no-argument CityRecord constructor

   // initialize a record
   public CustRecord( String custFirst, String custLast, int streetNum, String streetName, String streetType, String City, String State )
   {
      setCustFirst(  custFirst );
      setCustLast(  custLast );
      setStreetNum( streetNum );
      setStreetName( streetName );
      setCity( City );
      setState( State );
   } // end 6-argument CityRecord constructor

    public String getStreetType() {
        return streetType;
    }

    public void setStreetType(String streetType) {
        this.streetType = streetType;
    }
    public String getCustFirst() {
        return custFirst;
    }

    public void setCustFirst(String custFirst) {
        this.custFirst = custFirst;
    }

    public String getCustLast() {
        return custLast;
    }

    public void setCustLast(String custLast) {
        this.custLast = custLast;
    }

    public String getStreetName() {
        return streetName;
    }

    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }

    public int getStreetNum() {
        return streetNum;
    }

    public void setStreetNum(int streetNum) {
        this.streetNum = streetNum;
    }
   // set city name
   public void setCity( String cityName )
   {
      City = cityName;
   } // end method setCity

   // get city name
   public String getCity()
   {
       return City;
   } // end method getCity

   // set state name
   public void setState( String stateName )
   {
      State = stateName;
   } // end method setState

   // get state name
   public String getState()
   {
       return State;
   } // end method getState

} // end class CityRecord

All I have to do now is to take the state from the CustRecord constructor and place it into a collection. My instructor has STRONGLY recommended using a tree set since it contains no duplicates by default. I also need the states to be sorted alphabetically. There is no requirements as to output so I just intend to output the alphabetized collection to a generic output file (output.txt). I am a little confused as to how to build the collection and get the data from my constructor to the collection.
 

Answers and Replies

  • #2
117
3
Ok, I have constructed a new TreeSet, and am using a different input and output stream, so here is the new code for the main class. The supporting CustRecord class remains the same:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;
       FileOutputStream stateOut; // declare a file output object
       PrintStream p1; // declare a print stream object

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);

       try{

             // Create new file output streams
             stateOut = new FileOutputStream("StateList.txt", true); // output stream for states

             // Connect print streams to the output stream
             p1 = new PrintStream( stateOut );

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
            {
                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                State = scanner.next(); // reads to end of line sets the State
             }
             SortedSet StateSet = new TreeSet();
             StateSet.add(State);

             p1.print(StateSet);

             p1.close();

            }

        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
           System.err.println ("Error writing to file");
        }
    }
  }

The problem now is that I am getting an error printing to file when I try to execute.
I will work on debugging it and hope for someone to point me in the right direction
 
  • #3
117
3
OK, making more advances. New code as follows:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;
       FileOutputStream stateOut; // declare a file output object
       PrintStream p1; // declare a print stream object

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);

       try{

             // Create new file output streams
             stateOut = new FileOutputStream("StateList.txt", true); // output stream for states

             // Connect print streams to the output stream
             p1 = new PrintStream( stateOut );

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
            {
                SortedSet StateSet = new TreeSet();

                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                StateSet.add(scanner.next()); // reads to end of line sets the State

                p1.print(StateSet);
             }


             p1.close();


        }


        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
           System.err.println ("Error writing to file");
        }
    }
  }

Ok, now it creates the text file, and writes the states in, but there are duplicates and it is not in alphabetical order. I also still get the error writing to file on the main screen, but it does actually write the file. Here is the output and input:

input file:
Code:
Jonathan Smith 348 Front Circle Piedmont AL
Jessica Smith 431 Left Rd Chatom GA
Charles Stewart 25 South Blvd Paduca KY
Randy Jones 3532 Calioca St Mariannas CA
Otuoka Windtalker 5341 First St FirstTown AK
Jimmy Kimmel 1234 Second St LongBeach CA
Steven Tyler 5432 Wild Rd Mobile AL
James Hetfeild 6546 Metallica Blvd Rocking KY

and the output I get:

Code:
[AL][GA][KY][CA][AK][CA][AL][KY]

Any suggestions as to what I am doing wrong with my StateSet collection?
 
  • #4
117
3


OK, I don't know what is going on. Here is the code for my main class, custRecord unchanged

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;
       FileOutputStream stateOut; // declare a file output object
       PrintStream p1; // declare a print stream object

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);
      
       try{

             // Create new file output streams
             stateOut = new FileOutputStream("StateList.txt", true); // output stream for states

             // Connect print streams to the output stream
             p1 = new PrintStream( stateOut );

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
            {
                

                TreeSet< String > tree = new TreeSet< String >( Arrays.asList(State));


                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                tree.add(scanner.next()); // reads to end of line sets the State and adds the state to the TreeSet
                
                Iterator it1 = tree.iterator();

                while(it1.hasNext()){
                  System.out.println(it1.next());
                }                               
             }
                p1.close();
        }
        catch (Exception e)
        {
           System.err.println("Error Writing To File");
        }
      }
     
  }

Using the same input, here is the output:

output to screen:
Code:
run:

AL

GA

KY

CA

AK

CA

AL

KY
Error Writing To File
BUILD SUCCESSFUL (total time: 3 seconds)

and output to file:
Code:
[, AL][, AL][, GA][, GA][, KY][, KY][, CA][, CA][, AK][, AK][, CA][, CA][, AL][, AL][, KY][, KY]

I need the list to do 2 things:

1. NO DUPLICATES
2. SORT ALPHABETICALLY

It was my understanding, according to my instructor, that a TreeSet cannot contain duplicates, but it is apparent from the output that a TreeSet CAN have duplicates, or I am doing something terribly wrong. Could someone please go over this code and tell me what I am doing wrong?

BTW This assignment is due TONIGHT
 
  • #5
35,232
7,053
The best I can do is point you to the Java documentation for TreeSet and SortedSet. Just do a Web search for "java TreeSet" or "java SortedSet". I don't have any experience with these types - sorry. And Grep doesn't seem to be around.
 
  • #6
117
3
The best I can do is point you to the Java documentation for TreeSet and SortedSet. Just do a Web search for "java TreeSet" or "java SortedSet". I don't have any experience with these types - sorry. And Grep doesn't seem to be around.

Problem solved, thanks for the offer though. I toughed it out, and kind of posted questions to the board as I worked my way through the program. I actually figured it out by "Talking to the forum" LOL.
 

Related Threads on JAVA Collections (tree set)

  • Last Post
Replies
21
Views
4K
  • Last Post
Replies
4
Views
914
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
3
Views
922
Replies
37
Views
3K
  • Last Post
Replies
6
Views
789
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
3
Views
1K
  • Last Post
Replies
4
Views
2K
Top