Java GUI output to text file

  1. Develop an application that reads city, state and population entered from the user and writes this information to a file. The application should continuously prompt for this population information until terminated by the user.

    Example file:
    Jamestown FL 50000
    Domville CO 10000
    Jennyboro FL 30000
    Blountsville CO 5000

    Ok, first of all, I have decided to use a GUI for this project, which is optional, but I feel should be the appropriate format because that is what most applications will require in real world programming. I have most of the form working. It has a clear button, quit button, Enter Data Button, and Print to file button:

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

    /*
     * populationForm.java
     *
     * Created on Feb 16, 2011, 12:06:59 PM
     */

    /**
     *
     * @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();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            city = new javax.swing.JTextField();
            state = new javax.swing.JTextField();
            population = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jButton4 = new javax.swing.JButton();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jLabel1.setText("Population File Creator");

            jLabel2.setText("City:");

            jLabel3.setText("State:");

            jLabel4.setText("Population:");

            jButton1.setText("Clear Form");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });

            jButton2.setText("Create File");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });

            jButton3.setText("Quit");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });

            jButton4.setText("Enter Data ");
            jButton4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton4ActionPerformed(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(140, 140, 140)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addContainerGap())
                .addGroup(layout.createSequentialGroup()
                    .addGap(30, 30, 30)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel2)
                        .addComponent(jLabel4))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(city, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
                        .addComponent(state)
                        .addComponent(population))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 109, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap(10, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(50, 50, 50)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(city, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1))
                    .addGap(33, 33, 33)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2))
                    .addGap(41, 41, 41)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(population, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton3))
                    .addGap(38, 38, 38)
                    .addComponent(jButton4)
                    .addContainerGap(32, Short.MAX_VALUE))
            );

            pack();
        }// </editor-fold>

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
           city.setText("");
           state.setText("");
           population.setText("");
        }

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            System.exit(0);
        }

        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            city.getText();
            state.getText();
            population.getText();
        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        }

        /**
        * @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 jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JButton jButton4;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JTextField population;
        private javax.swing.JTextField state;
        // End of variables declaration

    }
     
    I know where the code needs to go, but I don't know a whole lot about the java IO stream. When the user clicks on the Enter Data button, I need the text in the text fields (city, state, & population) to be set and the form cleared. I guess an array would be the best way to store the information. The user should be able to continue to enter data as long as there is data to be entered, and then upon clicking the Print To File button, a text file should be created that displays the data in a format similar to the example file above.
     
  2. jcsd
  3. Ok, so the Instructor has added a new bit of requirements to this program. I now have to include a class (CityRecord) and use this class as the base for getting and setting text from my text fields. New Code is as follows:

    Java Form:

    Code (Text):
    /*
     * 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.*;
    /**
     *
     * @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">//GEN-BEGIN:initComponents
        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();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jButton4 = new javax.swing.JButton();

            jLabel1.setText("jLabel1");

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jLabel2.setText("Population Form");

            jLabel3.setText("City:");

            jLabel4.setText("State:");

            jLabel5.setText("Population");

            jButton1.setText("Clear Form");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });

            jButton2.setText("QUIT");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });

            jButton3.setText("Print to File");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });

            jButton4.setText("Enter Data");

            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(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(jButton3))
                    .addGap(58, 58, 58))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(227, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGap(212, 212, 212))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(162, Short.MAX_VALUE)
                    .addComponent(jButton4, 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(jButton1))
                    .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(jButton2))
                    .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(jButton3))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                    .addComponent(jButton4)
                    .addContainerGap())
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
            // When Clear Button is pressed, clear all text fields
            city.setText("");
            state.setText("");
            population.setText("");

        }//GEN-LAST:event_jButton1ActionPerformed

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
            // When EXIT Button is pressed, exit application
            System.exit(0);
        }//GEN-LAST:event_jButton2ActionPerformed

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
            // 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 (CityRecord.java);     // ** Problem is here how do I fix it **

                            p.close();
                    }
                    catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }


        }//GEN-LAST:event_jButton3ActionPerformed

        /**
        * @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//GEN-BEGIN:variables
        private javax.swing.JTextField city;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JButton jButton4;
        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.JTextField state;
        // End of variables declaration//GEN-END:variables

    }
     
    CityRecord class:

    Code (Text):
    /*
     * 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 double population;

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

       // initialize a record
       public CityRecord( String city, String state, double population )
       {
          setCity( city );
          setState( state );
          setPopulation( population );
       } // end three-argument CityRecord constructor

     

       // set city name
       public void setCity( String cityName )
       {
          cityName = city;
       } // end method setCity

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

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

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

       // set population
       public void setPopulation( double pop )
       {
          pop = population;
       } // end method setPopulation

       // get Population
       public double getPopulation()
       {
          return population;
       } // end method getPopulation
    } // end class CityRecord

    /*************************************************************************
    * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and               *
    * Pearson Education, Inc. All Rights Reserved.                           *
    *                                                                        *
    * DISCLAIMER: The authors and publisher of this book have used their     *
    * best efforts in preparing the book. These efforts include the          *
    * development, research, and testing of the theories and programs        *
    * to determine their effectiveness. The authors and publisher make       *
    * no warranty of any kind, expressed or implied, with regard to these    *
    * programs or to the documentation contained in these books. The authors *
    * and publisher shall not be liable in any event for incidental or       *
    * consequential damages in connection with, or arising out of, the       *
    * furnishing, performance, or use of these programs.                     *
    *************************************************************************
    I need CityRecord to get the information from the jtextfields in the main class, and then print to a file population.txt could someone take a look and point me in the right direction?
     
    Last edited: Feb 17, 2011
  4. Mark44

    Staff: Mentor

    In the first of your files, you have identified a line a code with a problem. The line of code is
    p.println (CityRecord.java);

    This won't work since there is no java field/member in your CityRecord class.

    CityRecord is the name of a class, so to use it you will need to create an instance of this class that gets its values from the form. More about that later.

    Assuming that cityRecord is the instance, and that its fields have been initialized, you can get the information with these expressions:

    cityRecord.getCity()
    cityRecord.getState()
    cityRecord.getPopulation()

    To get the information from your form to initialize the cityRecord instance, you can do something like this:

    CityRecord cityRecord = new CityRecord(city, state, population);

    Caveat: I haven't done any Java programming for about 15 years, so the code above might need some adjustment to make it work. The basic idea in my use of the CityRecord constructor is that it gets its three values from in instance of the PopulationForm class.

    If populationForm is an instance of the PopulationForm class, the line above should be revised like this:

    CityRecord cityRecord = new CityRecord(populationForm.city, populationForm.state, populationForm.population);

    Hope this helps...
     
  5. Haven't read through the code in any detail, but this jumped out at me:

    Code (Text):
       // set city name
       public void setCity( String cityName )
       {
          cityName = city;
       } // end method setCity
    You did that in at least one other place. You clearly meant:

    Code (Text):
       // set city name
       public void setCity( String cityName )
       {
          city = cityName;
       } // end method setCity
     
  6. Ok, I have now made some major modifications to the code. New code is as follows:

    Main Class:
    Code (Text):
    /*
     * 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.ArrayList;
    /**
     *
     * @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");

            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 (cityRecordList);

                            p.close();
                    }
                    catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }


        }                                        

        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

        /**
        * @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:

    Code (Text):
    /*
     * 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 double population;

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

       // initialize a record
       public CityRecord( String city, String state, double 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( double pop )
       {
          population = pop;
       } // end method setPopulation

       // get Population
       public double getPopulation()
       {
         return population;
       } // end method getPopulation
    } // end class CityRecord

     
    Here are my problems:

    1. It seems as if everything is being done within the main class, and the CityRecord class is just taking up space, which is a problem because I am required to use the CityRecord class.

    2. Though I am able to print the Arraylist that is holding the information from the form, it is printing the memory location and not the data in the array.

    3. It prints all data on one continuous line instead of each element on it's own line. Any suggestions based on the new code?
     
    Last edited: Feb 17, 2011
  7. I would add a toString method to it that gives you a string formatted the way you want it, or at least some method that returns the formatted string.

    Might be a more elegant way I can't think of at the moment, but I think you'll have to iterate through the array. If you have a toString method, then you can just println each element.

    If you println each element, that problem should go away.
     
  8. Mark44

    Staff: Mentor

    CityRecord is not just taking up space. You are using it in your main class. It's really not much more than a container for city, state, and population, which makes it in essence a struct + some accessor methods.
    You are attempting to print the contents of the ArrayList using a call to println, which doesn't know what to do with the address of an array of class objects.

    Instead, write an output method that takes an ArrayList parameter, and then loop through each of the CityRecord elements in the array. You will need to figure out some mechanism to make the loop halt when you run out of CityRecord objects.

    Within each CityRecord element, use println to print the city, state, and population.
    See above.
     
  9. Ok, glad to know that the CityRecord class is being used. I was scared there for a minute. As for the output method, I am not sure what you mean. I know I need a for loop to iterate through the array, but after struggling with this all day I am not really sure where to start with the for loop.

    My guess would be since I want it to print when the user click the Print To File Button, that is where the loop would go?

    I will work from there and try to hammer it out.
     
  10. From the function that handles the button click, yeah. Or as Mark said, make a separate function just to print the array and call it from there.

    Ok, the ArrayList class has a method called size() that will return the number of elements in it. You can use that in a for loop. Something as simple as:
    Code (Text):
    for (int i = 0; i < cityRecordList.size(); i++) {
        p.println(cityRecordList[i]);
    }
    Or you can use a foreach type construct (which is clearer and I recommend it):

    Code (Text):
    for (CityRecord rec : cityRecordList) {
        p.println(rec);
    }
    For that you need to override the default Object class toString() method in the CityRecord class:

    Code (Text):
    public String toString() {
        return city + " " + state + " " + population;
    }
    Didn't try and compile those but that should be enough so you know what I mean.
     
    Last edited: Feb 17, 2011
  11. Ok, tried the second method:

    code for Print To File Button:
    Code (Text):
     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");
                            for (CityRecord rec : cityRecordList) {
                                p.println(rec);

                    }
    I also created a toString method in CityRecord:

    Code (Text):
     public String toString() {
        return (city + " " + state + " " + population);
    }
    but I am not sure what you mean by
    When I try to compile:

    error:
    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\PopulationForm.java:175: incompatible types
    found : java.lang.Object
    required: phase4dbpopulation.CityRecord
    for (CityRecord rec : cityRecordList) {
    Note: C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\PopulationForm.java uses unchecked or unsafe operations.
     
  12. Mark44

    Staff: Mentor

    I think you need something like this (+ the missing right brace)
    Code (Text):

    for (CityRecord rec : cityRecordList)
    {
       p.println(rec.ToString());
    }
     
    rec.ToString returns a string that contains the city, state, and population, and println prints that string.
     
  13. Ok, with this code:

    Code (Text):
     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 ("Population by city and state");
                            for (CityRecord rec : cityRecordList) {     // Shows error occurring here
                                p.println(rec.toString());

                    }


                            p.close();
                    }
                            catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }


        }                                        
    I still get the error:

    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\PopulationForm.java:176: incompatible types
    found : java.lang.Object
    required: phase4dbpopulation.CityRecord
    for (CityRecord rec : cityRecordList) {

    and I don't see a missing brace?
     
  14. Oh, I get it. You didn't tell the compiler that your ArrayList will only contain CityRecord objects. You need to declare it so:

    Code (Text):
    ArrayList<CityRecord> cityRecordList = new ArrayList<CityRecord>();
     
    As for the missing brace, I thought you were missing one too, but it's just that your indentation is poor. And now you know why indentation is so very important!

    Oh yeah, you shouldn't need the .toString() in 'p.println(rec.toString());'. As for the method itself, if you added it to the CityRecord class, then you just overrode the Object.toString() method. You know about subclasses, superclasses and inheritance in general?

    Basically, all classes in Java have a base class (superclass) of Object. So CityRecord inherits from the Object class, and inherits various methods such as toString(). Now the default toString() in Object probably doesn't do what you want, so you implement your own version which overrides the one in the Object superclass. Due to what's called polymorphism, when someone tries to call toString on your object (even if they don't know that it's a CityRecord class - like if they have an array of various objects including yours), they will end up calling your toString method.

    The toString method should get used automatically if you print the object to a stream.

    If you're unclear on inheritance and such, I strongly suggest you look it up and learn about it. It's rather vital information.
     
  15. OK, finally, all of the errors are gone. There is only one final issue that I am trying to work out. Apparently, I have messed up when pulling the data from the array for printing. I am pretty sure it is in my CityRecord class.

    code is as follows now:

    Main Class:

    Code (Text):
    /*
     * 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");

            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");
                            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;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());

            // create a CityRecord object
            CityRecord cityRecord = new CityRecord();

            // 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:

    Code (Text):
    /*
     * 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 double population;

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

       // initialize a record
       public CityRecord( String city, String state, double 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( double 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

     
    The program compiles and runs correctly, but the output is wrong. This is all I get:

    Population by city and state
    0.0
     
  16. Mark44

    Staff: Mentor

    Maybe there isn't a missing brace, but your formatting fooled me. This is how I would indent things.
    Code (Text):

    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 ("Population by city and state");
       for (CityRecord rec : cityRecordList)
       {    
          // Shows error occurring here
          p.println(rec.toString());
       }

       p.close();
    }

    catch (Exception e)
    {
       System.err.println ("Error writing to file");
    }
     
    For the error you are seeing, the compiler seems to be saying it wants you to qualify CityRecord.
     
  17. Mark44

    Staff: Mentor

    In this method, when you create a CityRecord object, you use the wrong constructor - the one that sets the city and state to empty strings, and the population to 0.0. You should instead call the constructor that takes three args. I.e., do this:
    CityRecord cityRecord = new CityRecord(cityName, stateName, populationNum);

    Code (Text):

    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();

            // Add elements to array list
            cityRecordList.add(cityRecord);

            city.setText("");
            state.setText("");
            population.setText("");
        }  
     
     
  18. Indeed it seems to work properly with Mark's fix.

    Only comment I'd make is that it would be nice if you fixed the tab order on the form so it goes from field to field before going through the buttons. Was annoying having to click with the mouse on the next field.
     
  19. Mark44

    Staff: Mentor

    One minor thing I would add is about the comments in your accessor methods in CityRecord.
    Code (Text):

       // set city name
       public void setCity( String cityName )
       {
          city = cityName;
       } // end method setCity
     
    The "end method set/getXxx" comments don't add any information so aren't useful, especially in those very short methods. I would remove those "end" comments.
     
  20. Mark44, Grep, thank you both so much for your help. I have got it running. It is awesome. The only thing I want to change is being able to check the Population text field for integers and throw an error message up if data is invalid, say letters instead of numbers, but I think I can figure that one out. I am still open for ideas though, if you guys are interested.
     
  21. Mark44

    Staff: Mentor

    Not to beat a dead horse, but indentation is very important to help other readers understand what you're doing. Both grep and I were confused by what you were doing with the braces in one of your methods. In your latest iteration of that method, you have this:
    Code (Text):

    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");
                            for (CityRecord rec : cityRecordList) {
                                p.println(rec);

                            }


                            p.close();
                    }
                            catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }

     
    You fixed the brace for the for loop so now we can easily see what statements are part of that loop. However, the indentation you have makes it hard to find the catch block.

    The catch keyword should be at the save level of indentation as the try keyword, like so.
    Code (Text):

    try
    {
       // some statement(s)
    }

    catch ( some exception)
    {
       // do something
    }
     
    Notice that the beginning and ending braces for both blocks are lined up with their associated keyword. IMO, that's the best way to do it, but there's another point of view about where the leading brace should go.

    In any case there is no reason for the braces to be indented a whole tab stop or more.
     
Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook