Page 2 of 2 FirstFirst 12
Results 21 to 30 of 30
  1. #21
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Almost. The ArrayList should be generic (if this is allowed):

    Java Code:
    ArrayList<CityRecord> cityRecordList = new ArrayList<CityRecord>();
    Regardless, you don't want to add cityName, stateName and populationNum individually to the ArrayList. Please re-read my recommendations above carefully on what should be added:

    Sorry, but I am not sure what you mean by it needs to be generic. It is allowed due to the fact that the instructions from earlier in this discussion are literally the only constraints placed on me.

    I am now working on building the cityRecord object to pull the information so I can do as you suggested.

  2. #22
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Ok,I have built the object and set the button to enter the data in the array, and then clear the text fields:

    Java Code:
     private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
    
            CityRecord cityRecord = new CityRecord("city","state",0.0);
            cityRecordList.add(cityRecord);
    
            city.setText("");
            state.setText("");
            population.setText("");
        }                                        
    
        // Create an array list that can grow as data is input by user
        ArrayList cityRecordList = new ArrayList();
    
        // Add elements to array list
    I have also gotten the print button to print the array list:
    Java Code:
    private void printToFileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When PRINT TO FILE Button is pressed, print all entered data to file population.txt
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
    
            try
                    {
                            // Create a new file output stream
                            // connected to "population.txt"
                            out = new FileOutputStream("population.txt");
    
                            // Connect print stream to the output stream
                            p = new PrintStream( out );
    
                            p.println (cityRecordList);
    
                            p.close();
                    }
                    catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }
    Now here are the issues that I am having:
    1. I don't think I am using the CityRecord class. It seems that I am doing everything with just the main class

    2. The array is printing as follows:
    [phase4dbpopulation.CityRecord@7d742700, phase4dbpopulation.CityRecord@54acb158]
    instead of the data in the array, it is printing the memory location

    3. I need the data to print on individual line. as follows:

    Array Element 1
    Array Element 2
    Array Element 3

    Any suggestion, LOL

  3. #23
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by iamjonsmith View Post
    Ok,I have built the object and set the button to enter the data in the array, and then clear the text fields:

    Java Code:
     private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
    
            CityRecord cityRecord = new CityRecord("city","state",0.0);
            cityRecordList.add(cityRecord);
    
            city.setText("");
            state.setText("");
            population.setText("");
        }

    Good, you're creating a CityRecord object here and adding it to the array list. A problem I see is that you're passing 0.0 as the CityRecord's population and are ignoring the number that the user entered into the population JTextField, and that you've converted conveniently into a double.

    Java Code:
        // Create an array list that can grow as data is input by user
        ArrayList cityRecordList = new ArrayList();
    
        // Add elements to array list
    You're adding elements into the array list in your enterDataButtonActionPerformed, so no need for the comment (though it doesn't harm your code).


    I have also gotten the print button to print the array list:
    Java Code:
    private void printToFileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When PRINT TO FILE Button is pressed, print all entered data to file population.txt
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
    
            try
                    {
                            // Create a new file output stream
                            // connected to "population.txt"
                            out = new FileOutputStream("population.txt");
    
                            // Connect print stream to the output stream
                            p = new PrintStream( out );
    
                            p.println (cityRecordList);
    
                            p.close();
                    }
                    catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }
    Now here are the issues that I am having:
    1. I don't think I am using the CityRecord class. It seems that I am doing everything with just the main class

    2. The array is printing as follows:
    [phase4dbpopulation.CityRecord@7d742700, phase4dbpopulation.CityRecord@54acb158]
    instead of the data in the array, it is printing the memory location

    3. I need the data to print on individual line. as follows:

    Array Element 1
    Array Element 2
    Array Element 3

    Any suggestion, LOL
    Again, as I recommended in a post above, you will want to use a for loop to loop through the ArrayList. Inside the for loop, you'll get the i'th item in the ArrayList, which is a CityRecord object, and you'll use the get methods of CityRecord to extract the information held in the object's three fields, and then print this information. Then you'll call println inside the for loop.

  4. #24
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    I forgot to move the comment into the correct place after I moved the code, that is fixed.

    Ok, fixed the object to pull the city, state, and correct population:

    Java Code:
      private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
            
            // create a CityRecord object
            CityRecord cityRecord = new CityRecord(cityName,stateName,populationNum);
            // Add elements to array list
            cityRecordList.add(cityRecord);
    
            city.setText("");
            state.setText("");
            population.setText("");
        }
    I will get to work on the for loop for the array list now. Will I use the get methods in CityRecord to pull the information out of the array?

  5. #25
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by iamjonsmith View Post
    I forgot to move the comment into the correct place after I moved the code, that is fixed.

    Ok, fixed the object to pull the city, state, and correct population:

    Java Code:
      private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
            
            // create a CityRecord object
            CityRecord cityRecord = new CityRecord(cityName,stateName,populationNum);
            // Add elements to array list
            cityRecordList.add(cityRecord);
    
            city.setText("");
            state.setText("");
            population.setText("");
        }
    I will get to work on the for loop for the array list now. Will I use the get methods in CityRecord to pull the information out of the array?

    There are two types of for loops you can use, a standard for loop, in which case you'll use the get(int index) method of ArrayList to get each CityRecord object, or a foreach loop, in which case you won't need to do this, since each CityRecord is extracted for you (check the tutorials on how this works). If you don't use a generic ArrayList, (again an ArrayList<CityRecord>) then you'll have to cast the object returned by the ArrayList's get method into a CityRecord object.

    Java Code:
    CityRecord myCityRecord = (CityRecord)cityRecordList.get(i); // assuming that the for loop uses "i" as its index
    After you get the CityRecord object, then you will call its three get methods to get the information held in its three fields.

  6. #26
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Final Code:

    Main Class (jFrame form)
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /*
     * PopulationForm.java
     *
     * Created on Feb 14, 2011, 12:28:57 PM
     */
    
    package phase4dbpopulation;
    
    import java.io.*;
    import java.util.*;
    /**
     *
     * @author Jon and Jessica
     */
    public class PopulationForm extends javax.swing.JFrame {
    
        /** Creates new form PopulationForm */
        public PopulationForm() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            city = new javax.swing.JTextField();
            state = new javax.swing.JTextField();
            population = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            clearFormButton = new javax.swing.JButton();
            quitButton = new javax.swing.JButton();
            printToFileButton = new javax.swing.JButton();
            enterDataButton = new javax.swing.JButton();
    
            jLabel1.setText("jLabel1");
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jLabel2.setText("Population Form");
    
            city.setNextFocusableComponent(state);
    
            state.setNextFocusableComponent(population);
    
            jLabel3.setText("City:");
    
            jLabel4.setText("State:");
    
            jLabel5.setText("Population");
    
            clearFormButton.setText("Clear Form");
            clearFormButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearFormButtonActionPerformed(evt);
                }
            });
    
            quitButton.setText("QUIT");
            quitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quitButtonActionPerformed(evt);
                }
            });
    
            printToFileButton.setText("Print to File");
            printToFileButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    printToFileButtonActionPerformed(evt);
                }
            });
    
            enterDataButton.setText("Enter Data");
            enterDataButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    enterDataButtonActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(52, 52, 52)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5))
                    .addGap(29, 29, 29)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(city, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                        .addComponent(state)
                        .addComponent(population))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 157, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(clearFormButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(quitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(printToFileButton))
                    .addGap(58, 58, 58))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(233, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGap(212, 212, 212))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(168, Short.MAX_VALUE)
                    .addComponent(enterDataButton, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(139, 139, 139))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addGap(38, 38, 38)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(city, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(clearFormButton))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(quitButton))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(population, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(printToFileButton))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                    .addComponent(enterDataButton)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>
    
        private void clearFormButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When Clear Button is pressed, clear all text fields
            city.setText("");
            state.setText("");
            population.setText("");
    
        }                                        
    
        private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When EXIT Button is pressed, exit application
            System.exit(0);
        }                                        
    
        private void printToFileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When PRINT TO FILE Button is pressed, print all entered data to file population.txt
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
    
            try
            {
                 // Create a new file output stream
                 // connected to "population.txt"
                 out = new FileOutputStream("population.txt");
    
                 // Connect print stream to the output stream
                 p = new PrintStream( out );
    
                 p.println ("Population by City and State");
                 p.println("----------------------------");
                 for (CityRecord rec : cityRecordList) 
                 {
                    p.println(rec);
    
                 }
    
    
                    p.close();
             }
             catch (Exception e)
             {
                            System.err.println ("Error writing to file");
             }
    
    
        }                                        
    
        private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            int populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Integer.parseInt(population.getText());
    
            // create a CityRecord object
            CityRecord cityRecord = new CityRecord(cityName, stateName, populationNum);
    
            // Add elements to array list
            cityRecordList.add(cityRecord);
    
            city.setText("");
            state.setText("");
            population.setText("");
        }                                        
    
        // Create an array list that can grow as data is input by user
        ArrayList<CityRecord> cityRecordList = new ArrayList<CityRecord>();
       
        /**
        * @param args the command line arguments
        */
    
    
        public static void main(String args[]) {
                java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PopulationForm().setVisible(true);
                }
            });
    
        }
    
        // Variables declaration - do not modify
        private javax.swing.JTextField city;
        private javax.swing.JButton clearFormButton;
        private javax.swing.JButton enterDataButton;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JTextField population;
        private javax.swing.JButton printToFileButton;
        private javax.swing.JButton quitButton;
        private javax.swing.JTextField state;
        // End of variables declaration
    
    }
    CityRecord Class:

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package phase4dbpopulation;
    
    /**
     *
     * @author Jon and Jessica
     */
    // Fig. 17.5: CityRecord.java
    // CityRecord class maintains information for one account.
     // packaged for reuse
    
    public class CityRecord
    {
    
       private String city;
       private String state;
       private int population;
    
       // no-argument constructor calls other constructor with default values
       public CityRecord()
       {
          this(  "", "", 0 ); // call three-argument constructor
       } // end no-argument CityRecord constructor
    
       // initialize a record
       public CityRecord( String city, String state, int population )
       {
          setCity(  city );
          setState(  state );
          setPopulation( population );
       } // end three-argument CityRecord constructor
    
      
    
       // 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
    
       // set population
       public void setPopulation( int pop )
       {
          population = pop;
       } // end method setPopulation
    
       // get Population
       public double getPopulation()
       {
         return population;
       } // end method getPopulation
    
       public String toString() {
        return (city + " " + state + " " + population);
    }
      
    } // end class CityRecord

  7. #27
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Cool, you're almost there. Check that population.txt file though as you're writing out the default toString() from the Object class. To get this code to work, you'll want to either give CityRecord its own public String toString() method, one that prints returns the name of the city, the state and the population, or else do what I suggested earlier -- use the methods of CityRecord to extract this information from each item in the array list, and then print that out.

  8. #28
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    As far as I can tell, with the code as is, the file prints out correctly. The only issue I have run into so far is data validation for the population field. If the user enters a number into the population field, the IDE throws an error, but does continue to run the program. I am trying to figure out how to validate the data for the population field and only allow integers.

  9. #29
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by iamjonsmith View Post
    As far as I can tell, with the code as is, the file prints out correctly.

    Then your CityRecord already has a toString() method? I suppose it must else this wouldn't work.



    The only issue I have run into so far is data validation for the population field. If the user enters a number into the population field, the IDE throws an error, but does continue to run the program. I am trying to figure out how to validate the data for the population field and only allow integers.

    You are parsing it as a double. Do you mean to parse it as an int? Regardless, look up the tutorial on Java exceptions, in particular the part on using try/catch blocks. You'll want to catch a NumberFormatException in this situation.

  10. #30
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    I guess I didn't post the updated code for the CityRecord class, but Yes, I did end up building a toString method so that it would work as you suggested. I also ended up changing the code to parse an integer.

    As for the data validation for catching the unwanted data, I am going to fool with that tomorrow. I am just too tired to keep on with it tonight. Thanks for all of the help, it has been much appreciated.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. Print info from a different class?
    By liquidtoon in forum New To Java
    Replies: 3
    Last Post: 11-01-2010, 02:19 PM
  2. Print Array as String through class file?
    By ocarabal in forum New To Java
    Replies: 3
    Last Post: 06-08-2010, 06:22 AM
  3. Print Variable From One Class to Output on another.
    By Lyricid in forum New To Java
    Replies: 8
    Last Post: 02-27-2010, 02:56 PM
  4. Replies: 3
    Last Post: 03-19-2009, 06:00 PM
  5. Print the text file and print preview them
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-23-2008, 12:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •