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: Program that selectively outputs data from a text file.

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation Program that selectively outputs data from a text file.

    Hi all,
    I would greatly appreciate any help I could get with this program (which is described below) , together with the code I’ve written, as I’m getting a lot of errors in the code which suggests I’m seriously off track. Thanks very much.
    __________________________________________________ ________________________________
    Program:
    The city periodically goes through its records and schedules property inspections (e.g., for lead or rodents). You will complete a Java application that reads a list of property data from a file and determines what kinds of inspections should be scheduled (if any). When properties contain multiple units (e.g., apartments), an inspection is scheduled for the entire building; however, the types of inspections are determined based on data concerning each unit.

    Output of the completed program should look like (sample run, user input in bold):

    Owner Street Unit Built
    Bill Jannings 1 College Way 2000
    Danielle Parsons 1200 Beacon St. 7 1998
    Terry Hawkings 1200 Beacon St. B 1999
    Greg Royal 1200 Beacon St. 17 1998
    Dennis Howe 15 Boltoph St. 1 1885
    Soi Fong 15 Boltoph St. 2 1885
    William Burrows 15 Boltoph St. 5 1885
    Ken Dahal 247 Harvard Ave. 1899
    Inspections:
    1 College Way:
    1200 Beacon St.: rodents
    15 Boltoph St.: lead rodents
    247 Harvard Ave.: lead

    Outline
    1. Reads all property data from file (properties.txt) into array.
    2. Displays property data: owner name, street address, unit (if any), and year built.
    3. Displays the inspections scheduled for each building.

    Property Class
    The Property class represents data for a single property within the city.
    Data Members
    The code provided includes the following data members:
    • owner: owner’s name.
    • streetAddress: street address without the unit number.

    •unit: unit information (may be in various formats: “Unit #B”, “Apt. B”, etc.).
    • builtYear: year unit was built (or when building was built, if there aren’t separate units).
    Methods
    The code provided includes a default constructor as well as some accessors and mutators. You must complete 3 methods within the class (headers below):
    1. Method to set the address:

    public void setAddress(String newAddress)
    This method should break the address passed into its street address and unit. Assume the unit (if any) follows a comma (,). If there is no unit listed, store the empty string as the unit. Look up appropriate String class methods to find the comma in a string, etc.
    2. Constructor to initialize the object using the values passed:

    public Property(String initOwner,
    String initAddress,
    int initBuiltYear)

    This constructor should initialize all data members using its parameters. As part of its definition, call method setAddress (see above) to set the address, thus initializing the street address and unit members. Currently, the default constructor and “set” methods are used in method loadProperties [Inspections.java] to initialize each property record stored in an array. Change the code to instead use this constructor.
    3. Method to extract the number (or letter, etc.) of the unit:

    public String getUnitNum()
    This method should return a string containing only the unit number. For example, units are stored in various ways within the property data file: Apt. 7, Unit #2, simply #17, or even just B. This method should not change how the unit is stored within the Property class, it should only extract and return the unit number (here, 7, 2, 17, and B) and returns it.
    This will again require using String class methods. Examine the property data file properties.txt to see all the formats used. This method is called from method displayProperties [Inspections.java].
    Main Program (Class Inspections)
    The main program (class Inspections) is divided into methods. Notably, method loadProperties returns an array. Recall that a Java array is stored using a reference. A couple methods list throws clauses (throws FileNotFoundException) since opening a file may cause an exception that the code does not catch.
    As stated in 2. under “Methods” above, in method loadProperties, instantiate each Property object using the constructor (with arguments) that you wrote [Property.java].
    Complete method scheduleInspections to display scheduled inspections for buildings. The method will not list inspections for every unit, only for each building (unique street address). Call that method from main.
    For example, reviewing the sample run:
    Owner Street Unit Built
    Bill Jannings 1 College Way 2000
    Danielle Parsons 1200 Beacon St. 7 1998
    Terry Hawkings 1200 Beacon St. B 1999
    Greg Royal 1200 Beacon St. 17 1998
    Dennis Howe 15 Boltoph St. 1 1885
    Soi Fong 15 Boltoph St. 2 1980
    William Burrows 15 Boltoph St. 5 1885
    Ken Dahal 247 Harvard Ave. 1899
    Inspections:
    1 College Way:
    1200 Beacon St.: rodents
    15 Boltoph St.: lead rodents
    247 Harvard Ave.: lead
    The schedule does not show “1200 Beacon St.” multiple times; instead it appears only once for its 3 units. Below outlines how method scheduleInspections displays output for each building only once:
    • Declares a variable to keep track of the last street address seen.
    • Loops through each of the properties.
    • If a property’s street address is the same as the last street address seen, then we must be in the same building (assumes property records for a particular building are contiguous). Note how it correctly compares strings.
    • If the street address changes, outputs the address of the building (right now it doesn’t output any inspections).

    You must add code to determine and output inspections as follows:
    • If any unit in a building was built before 1970, schedule a “lead” inspection. Add an appropriate constant.
    • If there is more than one unit in a building, schedule a “rodent” inspection.
    • Eliminate the spurious output that appears for the first property record.
    To determine these inspections, you must track the earliest (minimum) “year built” for each building (among all its units). In addition, your must count the number of units in a building.

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    My ( error-filled ) code is as follows. It contains a parent (main) class called Inspections & a child class called Property .

    (a) Inspections (main):

    /*
     * File: Inspections.java
     * Date: Monday, September 17th 2012.
     * Description: A Java application,
     * that reads a list of property data from a file,
     * and determines what kinds of inspections should be scheduled (if any). 
     */
     
    import java.util.*;  // for Scanner
    import java.io.*;    // for FileReader
     
    public class Inspections
       {
       // Load all property records from file.
       public static void  loadProperties()
       throws FileNotFoundException   // unhandled exception for FileReader
     
       {
       String[] owner = new String[8];
       String[] streetAddress = new String[8];
       String[] unit = new String[8];
       int[] builtYear = new int[8];
     
       }
     
     
     
       public static Scanner console = new Scanner(System.in);
     
       public static void main(String[] args)
          throws FileNotFoundException
       {
          Property[] allProperties = loadProperties(Property.Properties);
     
          // CALL METHOD scheduleInspections
             scheduleInspections( );
     
     
          displayProperties(allProperties);
     
          // Allow user to enter names of properties
     
          System.out.print("Enter name of property:  ");
          String name = console.nextLine( );
     
          Property property1 = new Property(name);
          System.out.println("Initial status: " + property1);
     
     
          // Loop through each of the properties
          final int REQUIREMENT_FOR_RODENT_INSPECTION = 2;
     
          while(property1.getScheduleInspections( ) > 0)
          {
           // Determine if inspection required
           if(property1.getUnit()< REQUIREMENT_FOR_RODENT_INSPECTION)
           {
            System.out.println("Schedule rodent inspection");
            }
            else if (property1.getYear() < 1970)
            {
             System.out.println("Schedule lead inspection");
             }
     
     
          Scanner condFile = new Scanner(new FileReader("properties.txt"));
     
          int numPropertys = condFile.nextInt();  // # of records in file
     
          // Create array large enough for all records in file.
          Property[] readProperties = new Property[numPropertys];
     
          // Read in all weather property data.
          for (int i = 0; i < readProperties.length; i++)
          {
             condFile.nextLine();  // eat newline since just read number
             String owner = condFile.nextLine();
             String address = condFile.nextLine();
             int year = condFile.nextInt();
     
             // REPLACE DEFAULT CONSTRUCTOR AND "set" CALLS WITH
             // USE OF CONSTRUCTOR THAT TAKES ARGUMENTS.
             readProperties[i] = new Property(owner,address,year);  //readProperties[i] = new Property();
               //readProperties[i].setOwner(owner);
             //readProperties[i].setAddress(address);
             //readProperties[i].setBuiltYear(year);
          }
     
          return readProperties;
       }
     
    // Display formatted  data......started  here
             }
          }
       //}
     
          // Display formatted data for each property.
         public static void displayProperties(Property[] showProperties)  //                     line 100  - ERRORS
     
        {
          System.out.printf("%-20s%-25s%-9s%-7s%n",
             "Owner", "Street", "Unit", "Built");
       //}
     
          for (int i = 0; i < showProperties.length; i++)                                          //  line  106  -  ERRORS
          {
             System.out.printf("%-20s%-25s%-9s%-7d%n",
                showProperties[i].getOwner(),
                showProperties[i].getStreetAddress(),
                showProperties[i].getUnitNum(),
                showProperties[i].getBuiltYear() );
          }                                                                                                          //  line  113  -  ERROR
       }
     
       // Display needed inspections for each building.
          String rodent;
          String lead;                                                                                             //  line  118  - ERROR
       // COMPLETE METHOD scheduleInspections
    // public static void scheduleInspections(Property[] inspectProperties)
       {                                                                                                               //  line  121  -  ERROR
         String lastAddress = "";
     
          System.out.println("\nInspections:");                                                        //  line  124  -  ERROR
     
          for (int i = 0; i < inspectProperties.length; i++)                                         //  line  126  -  ERROR
          {
             String currAddress = inspectProperties[i].getStreetAddress();
     
             if (!currAddress.equals(lastAddress))                                                      //  line  130  -  ERROR
             {
                System.out.print(lastAddress + ":");
                System.out.println();                                                                         //  line  133  -  ERROR
     
                lastAddress = currAddress;                                                                //  line  135  -  ERROR
     
             }}}                                                                                                     //  line  137  -  ERROR
       }  
       }
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    (b) Property (child) class:

    /*
     * File: Property.java
     * Date: Monday 24th September 2012.
     * Description: Property class is a subclass of Inspections.
     */
     
    import java.util.*;  // for Scanner
     
    public class Property
    {
       private String owner;
       private String streetAddress;
       private String unit;
       private int builtYear;
     
       // "default constructor" called when no arguments
       // given during instantiation.
       public Property()
       {
          owner = "";
          streetAddress = "";
          unit = "";
          builtYear = 0;
       }
     
       // ADD A CONSTRUCTOR THAT EXPECT ARGUMENTS WITH
       // INITIAL VALUES FOR DATA MEMBERS.
     
       public Property(String initOwner, String initAddress, int initBuiltYear)
       {
           owner = initOwner;
           setAddress(initAddress);     
           builtYear = initBuiltYear;
       }
     
     
       // "accessor" methods to give back values of data members.
     
       public String getOwner()
       {
          return owner;
       }
     
       public String getStreetAddress()
       {
          return streetAddress;
       }
     
       public String getUnit()
       {
          return unit;
       }
     
       public int getBuiltYear()
       {
          return builtYear;
       }
     
       public String getUnitNum()
       {
          // ADD CODE TO EXTRACT AND RETURN UNIT NUMBER.
          String num = "";
          for(int i = 0; i < unit.length; i++)                                                //  line  66  -  ERROR
          {     
             if(Character.isDigit(unit[i].charAt(0)))                                        //  line  68  -  ERROR
            {
                num = num + unit[i];                                                           //  line  70  -  ERROR
             }
             else
             {
             Character.isDigit(unit[i].charAt(unit.length - 1));                       //  line  74 -  ERRORS
             }    
         }
          return num;
       }
     
       // "mutator" methods to change values of data members.
     
       public void setOwner(String newOwner)
       {
          owner = newOwner;
       }
     
       public void setAddress(String newAddress)
       {
          // ADD CODE TO SEPARATE AND STORE THE
          // STREET ADDRESS AND UNIT.
         String [] newAddressSplit = newAddress.split(",",2);
     
         streetAddress = newAddressSplit[0];
         unit = newAddressSplit[1];
        }
     
       public void setBuiltYear(int year)
       {
          builtYear = year;
       }
     
        public void getScheduleInspections( )         // called from main                            //  line 104  - ERROR
        {
          return scheduleInspections;
        }
     
    }


    Compiler Error Messages:
     

    ----jGRASP exec: javac -g Inspections.java

    Inspections.java:100: error: class, interface, or enum expected
    public static void displayProperties(Property[] showProperties) //
    ^
    Inspections.java:106: error: class, interface, or enum expected
    for (int i = 0; i < showProperties.length; i++)
    ^
    Inspections.java:106: error: class, interface, or enum expected
    for (int i = 0; i < showProperties.length; i++)
    ^
    Inspections.java:106: error: class, interface, or enum expected
    for (int i = 0; i < showProperties.length; i++)
    ^
    Inspections.java:113: error: class, interface, or enum expected
    }
    ^
    Inspections.java:118: error: class, interface, or enum expected
    String lead;
    ^
    Inspections.java:121: error: class, interface, or enum expected
    {
    ^
    Inspections.java:124: error: class, interface, or enum expected
    System.out.println("\nInspections:");
    ^
    Inspections.java:126: error: class, interface, or enum expected
    for (int i = 0; i < inspectProperties.length; i++)
    ^
    Inspections.java:126: error: class, interface, or enum expected
    for (int i = 0; i < inspectProperties.length; i++)
    ^
    Inspections.java:126: error: class, interface, or enum expected
    for (int i = 0; i < inspectProperties.length; i++)
    ^
    Inspections.java:130: error: class, interface, or enum expected
    if (!currAddress.equals(lastAddress))
    ^
    Inspections.java:133: error: class, interface, or enum expected
    System.out.println();
    ^
    Inspections.java:135: error: class, interface, or enum expected
    lastAddress = currAddress;
    ^
    Inspections.java:137: error: class, interface, or enum expected
    }}}
    ^
    15 errors



    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.

    ----jGRASP exec: javac -g Property.java

    Property.java:66: error: cannot find symbol
    for(int i = 0; i < unit.length; i++)
    ^
    symbol: variable length
    location: variable unit of type String
    Property.java:68: error: array required, but String found
    if(Character.isDigit(unit[i].charAt(0)))
    ^
    Property.java:70: error: array required, but String found
    num = num + unit[i];
    ^
    Property.java:74: error: cannot find symbol
    Character.isDigit(unit[i].charAt(unit.length - 1));
    ^
    symbol: variable length
    location: variable unit of type String
    Property.java:74: error: array required, but String found
    Character.isDigit(unit[i].charAt(unit.length - 1));
    ^
    Property.java:104: error: cannot return a value from method whose result type is void
    return scheduleInspections;
    ^
    6 errors

    Last edited by helloworld922; September 22nd, 2012 at 04:18 PM. Reason: fixed formatting


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Program that selectively outputs data from a text file.

    Consider placing [code] [/code] tags around your posted code so that it retains its formatting and is readable. Also consider showing us the error messages, and then indicating with comments in the code the lines that cause the errors.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Program that selectively outputs data from a text file.

    Hi curmudgeon,
    I added the compiler messages, tagged the code, & left messages on the code saying where the errors occurred, like you suggested.
    Thanks.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Program that selectively outputs data from a text file.

    How to format your code (I fixed it for you this time):

    [code=java]
    // your code goes here
    [/code]


    Looks like this:

    // your code goes here

  5. #5
    Junior Member
    Join Date
    Sep 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Program that selectively outputs data from a text file.

    Thanks helloworld922, it looks great !

  6. #6
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Program that selectively outputs data from a text file.

    I made some stylistic changes to use consistent indentation and put in a few comments to emphasize (for Human readers) the block delineation. To reduce a clutter a little, I left out some of your comments, but you should put them back in to suit your sensibilities...

    Anyhow, here's the beginning of your Inspections.java
    /*
     * File: Inspections.java
     * Date: Monday, September 17th 2012.
     * Description: A Java application,
     * that reads a list of property data from a file,
     * and determines what kinds of inspections should be scheduled (if any). 
     */
     
    import java.util.*;
    import java.io.*;
     
    public class Inspections
    {
        public static void loadProperties() throws FileNotFoundException 
        {
            String [] owner = new String[8];
            String [] streetAddress = new String[8];
            String [] unit = new String[8];
            int [] builtYear = new int[8];
        }
        public static Scanner console = new Scanner(System.in);
     
        public static void main(String [] args) throws FileNotFoundException
        {
            Property [] allProperties = loadProperties(Property.Properties);
     
            scheduleInspections( );
     
            displayProperties(allProperties);
     
            System.out.print("Enter name of property:  ");
            String name = console.nextLine( );
     
            Property property1 = new Property(name);
            System.out.println("Initial status: " + property1);
     
            final int REQUIREMENT_FOR_RODENT_INSPECTION = 2;
     
            while(property1.getScheduleInspections() > 0)
            {
                if(property1.getUnit()< REQUIREMENT_FOR_RODENT_INSPECTION)
                {
                    System.out.println("Schedule rodent inspection");
                }
                else if (property1.getYear() < 1970)
                {
                    System.out.println("Schedule lead inspection");
                }
     
                Scanner condFile = new Scanner(new FileReader("properties.txt"));
     
                int numPropertys = condFile.nextInt(); 
     
                Property [] readProperties = new Property[numPropertys];
                for (int i = 0; i < readProperties.length; i++)
                {
                    condFile.nextLine();
                    String owner = condFile.nextLine();
                    String address = condFile.nextLine();
                    int year = condFile.nextInt();
     
                    readProperties[i] = new Property(owner,address,year);
                } // End of for (int i = 0; i < readProperties...)
     
                return readProperties;
            } // End of while(property1.getScheduleInspections...)
     
        } // End of main()
    } // End of class definition
     
    //  From Zaphod_b:
    ///    Where is this stuff supposed to go???
    //     Gotta be inside some class!
    //         |
    //         |
    //         |
    //         |
    //         V  (Line 80 is the public static void displayProperties(...)
        // Display formatted data for each property.
        public static void displayProperties(Property [] showProperties)
     
        {
            System.out.printf("%-20s%-25s%-9s%-7s%n",
            "Owner", "Street", "Unit", "Built");
    .
    .
    .

    Error messages start at line 80:
    ___________________________________

    Inspections.java:80: class, interface, or enum expected
    public static void displayProperties(Property[] showProperties)
    .
    . Lots of other messages...
    .

    ___________________________________


    Maybe this will be a start...

    Here's the thing:

    Most experienced programmers would recommend that you begin with as few lines as possible and make sure your basic stuff compiles cleanly. Maybe create function (method) definitions, but make the function bodies empty except for return statements where appropriate. Use consistent indentation so that inner blocks are indented more than outer blocks. Blocks should begin and end at the same column number. Stuff like that.

    Then, fill in the functions one at a time and recompile each time you add some stuff.


    Cheers!

    Z.
    Last edited by Zaphod_b; September 25th, 2012 at 11:46 AM.

Similar Threads

  1. Reading data from a text file into an object
    By surfbumb in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 6th, 2011, 08:37 PM
  2. Replies: 8
    Last Post: March 25th, 2011, 02:34 PM
  3. Program that reads data from a text file...need help
    By cs91 in forum Java Theory & Questions
    Replies: 4
    Last Post: October 3rd, 2010, 07:57 AM
  4. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM
  5. Read data from text file
    By yroll in forum Algorithms & Recursion
    Replies: 4
    Last Post: December 31st, 2009, 01:40 AM