Results 1 to 10 of 10
  1. #1
    dalythe is offline Member
    Join Date
    Mar 2013
    Posts
    27
    Rep Power
    0

    Default Printing the contents of my Array

    I am trying to get the contents of my Array into a variable that I can append to my text area. With the following code below, I only get the last value entered in the last column. Any suggestions?

    Java Code:
    public class TutorEarnings extends javax.swing.JFrame{
    //Instance Variable
        private double sessionMinutes; //tutor's session minutes
        private double sessionEarnings; //tutor's session earnings
        private double totalMin = 0.0; //total session minutes
        private double totalHr = 0.0; //total session hours
        private double totalEarn = 0.00; //total session earnings
        private double wage; //unformatted wage
        private double avgWage;  //tutor's average wage per hour
        private final double minWage = 7.25;//current national minimum wage per hour
        private String areaMessage; //message to be dispaly in Text Area
        String newline = "\n"; //carriage return
        String tab = "\t"; //tab space
        char dollar = '$'; //dollar sign
        char period = '.'; //period
        String ast = "*****************";  //report border
        double data[][] = new double[5][2]; //input data array
        int sessionRows = 0; //number of rows in the array
        String statement1 = new String("Raw Tutoring Earnings Data");
        String statement2 = new String("Report of your wages to Date:");
        String statement3 = new String("Total Minutes Spent Tutoring = ");
        String statement4 = new String("Total Earnings = ");
        String statement5 = new String("Average Per Hour Wage = ");
        String statement6 = new String("Minimum Wage is currently = ");
        String statement7 = new String("Your average wages per hour are ");
        String result; //result of analysis
        String prtData; //printed contents of the data array
        String sb1;  //first StringBuilder
        String sb1S; //converted String version of the first StringBuilder
        String sb2;  //second StringBuilder
        String sb2S; //converted String version of the second StringBuilder
     
        /**
         * Iterates through the data array, formats the output to the desired look,
         * and then stores the printed content to a variable
         * @return prtData
         */
        public String printArray(){
            for (int r=0; r < data.length; r++)
            {
                for (int c = 0; c < data[r].length; c++){
                    System.out.print("Minutes: " + data[r][c]);
                    
                    prtData = Double.toString(data[r][c]);
                }
                    
            }
            return prtData;
        }
    
       private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
           
            //Performing the required calculations for the report
            getMinTotal();
            getEarnTotal();
            getAvgWage();
            performAnalysis();
            printArray();
            
            //declaring and initializing the StringBuilders
            StringBuilder sb1 = new StringBuilder(ast + ast + ast + newline);
            StringBuilder sb2 = new StringBuilder(ast + ast + ast + newline + newline);
            
            //Constructing the desired output for the JTextArea
            sb1.append(statement1 + newline);
            sb1.append(newline + prtData + newline);
                    
            sb2.append(statement2 + newline + newline + statement3 + tab + totalMin);
            sb2.append(newline + statement4 + tab + dollar + totalEarn + newline);
            sb2.append(statement5 + tab + dollar + avgWage + newline + newline);
            sb2.append(statement6 + tab + dollar + minWage + newline + newline);
            sb2.append(statement7 + result + period);
            
            //converting the StringBuilders into the required String datatype
            sb1S = sb1.toString();
            sb2S = sb2.toString();
            
           //initializing the text area message variable and setting it to the tArea
            areaMessage = sb1S + newline + sb2S;
            tArea.setText(areaMessage);
    
        }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,617
    Rep Power
    5

    Default Re: Printing the contents of my Array

    You are not appending the data to prtData, only replacing the previous contents.

    Try this:

    Java Code:
     public String printArray() {
            for (int r=0; r < data.length; r++)
            {
                for (int c = 0; c < data[r].length; c++){
                    System.out.print("Minutes: " + data[r][c]);
                    prtData += Double.toString(data[r][c]); // this line was changed.
                }
            }
            return prtData;
    }
    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    dalythe is offline Member
    Join Date
    Mar 2013
    Posts
    27
    Rep Power
    0

    Default Re: Printing the contents of my Array

    By trying your suggestion, I did get output but NULL was at the beginning the output. I made the following change in hopes of getting the output to look like a matrix and get rid of the NULL. I had no such luck.

    Java Code:
    public String printArray(){
            for (int r=0; r < data.length; r++)
            {
                for (int c = 0; c < data[r].length; c++){
                    System.out.println("%8d"+ data[r][c]);                
                    prtData += Double.toString(data[r][c]);
                }
            }
            return prtData;
        }

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,617
    Rep Power
    5

    Default Re: Printing the contents of my Array

    Please include the rest of the code because the problem may lie elsewhere.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    dalythe is offline Member
    Join Date
    Mar 2013
    Posts
    27
    Rep Power
    0

    Default Re: Printing the contents of my Array

    Here it is :

    Java Code:
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.text.*;
    
    /**
     *Creates a GUI that accepts earning information per tutoring session
     *
     */
    public class TutorEarnings extends javax.swing.JFrame{
    //Instance Variable
        private double sessionMinutes; //tutor's session minutes
        private double sessionEarnings; //tutor's session earnings
        private double totalMin = 0.0; //total session minutes
        private double totalHr = 0.0; //total session hours
        private double totalEarn = 0.00; //total session earnings
        private double wage; //unformatted wage
        private double avgWage;  //tutor's average wage per hour
        private final double minWage = 7.25;//current national minimum wage per hour
        private String areaMessage; //message to be dispaly in Text Area
        String newline = "\n"; //carriage return
        String tab = "\t"; //tab space
        char dollar = '$'; //dollar sign
        char period = '.'; //period
        String ast = "*****************";  //report border
        double data[][] = new double[5][2]; //input data array
        int sessionRows = 0; //number of rows in the array
        String statement1 = new String("Raw Tutoring Earnings Data");
        String statement2 = new String("Report of your wages to Date:");
        String statement3 = new String("Total Minutes Spent Tutoring = ");
        String statement4 = new String("Total Earnings = ");
        String statement5 = new String("Average Per Hour Wage = ");
        String statement6 = new String("Minimum Wage is currently = ");
        String statement7 = new String("Your average wages per hour are ");
        String result; //result of analysis
        String prtData; //printed contents of the data array
        String sb1;  //first StringBuilder
        String sb1S; //converted String version of the first StringBuilder
        String sb2;  //second StringBuilder
        String sb2S; //converted String version of the second StringBuilder
    
        /**
         * Creates new form JFrame
         */
        public TutorEarnings() {
          initComponents();
        }
        /**
         * Calculates the total minutes from all tutoring sessions
         * @return totalMin
         */
        public double getMinTotal(){
            totalMin=0;
            for(int r=0;r<data.length;r++){
            totalMin+=data[r][0];
            }    
            return totalMin;
        }
        /**
         * Calculates the total earnings from all tutoring sessions
         * @return totalEarn
         */
        public double getEarnTotal(){
            DecimalFormat df = new DecimalFormat("##.00");
            totalEarn=0;
            for(int r=0;r<data.length;r++){
            totalEarn=data[r][1];
            }
            return totalEarn;
        }
        /**
         * Calculates the average per hour wage based on the total earnings 
         * @return avgWage
         */
        public double getAvgWage(){
            DecimalFormat df = new DecimalFormat("##.00");
            totalHr = totalMin / 60;
            wage = totalEarn / totalHr;
            avgWage = Double.parseDouble(df.format(wage));
            return avgWage;
        }
        /**
         * Performs a comparative analysis between the minimum wage and the average
         * per hour wage. Determines if average wage is below, above, or average 
         * with the minimum hourly wage
         * @return results
         */
        public String performAnalysis(){
            if (avgWage < minWage){
            result = "below average";
            }
            if ((avgWage >= minWage) && (avgWage <= (minWage * 2.00))){
            result = "average";
            }
            if (avgWage > (minWage * 2.00)){
                result = "above average";
            }
            return result;
        }
        /**
         * Iterates through the data array, formats the output to the desired look,
         * and then stores the printed content to a variable
         * @return prtData
         */
        public String printArray(){
            for (int r=0; r < data.length; r++)
            {
                for (int c = 0; c < data[r].length; c++){
                    System.out.println("%8d" + newline + data[r][c]);                
                    prtData += Double.toString(data[r][c]);
                }
            }
            return prtData;
        }
        /**
         * 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() {
    
            p1 = new javax.swing.JPanel();
            tBox1 = new javax.swing.JTextField();
            lbl1 = new javax.swing.JLabel();
            p2 = new javax.swing.JPanel();
            p3 = new javax.swing.JPanel();
            sP = new javax.swing.JScrollPane();
            tArea = new javax.swing.JTextArea();
            p4 = new javax.swing.JPanel();
            btn1 = new javax.swing.JButton();
            btn2 = new javax.swing.JButton();
            btn3 = new javax.swing.JButton();
            btn4 = new javax.swing.JButton();
            lbl2 = new javax.swing.JLabel();
            tBox2 = new javax.swing.JTextField();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Tutoring Wages Report");
            setBackground(new java.awt.Color(0, 153, 255));
            setName("f"); // NOI18N
    
            p1.setName("p1"); // NOI18N
    
            tBox1.setName("tBox1"); // NOI18N
    
            lbl1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
            lbl1.setText("Tutoring Time in Minutes");
            lbl1.setName("lbl1"); // NOI18N
    
            javax.swing.GroupLayout p1Layout = new javax.swing.GroupLayout(p1);
            p1.setLayout(p1Layout);
            p1Layout.setHorizontalGroup(
                p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(p1Layout.createSequentialGroup()
                    .addComponent(lbl1, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(tBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            p1Layout.setVerticalGroup(
                p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, p1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lbl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            );
    
            p2.setName("p2"); // NOI18N
    
            javax.swing.GroupLayout p2Layout = new javax.swing.GroupLayout(p2);
            p2.setLayout(p2Layout);
            p2Layout.setHorizontalGroup(
                p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 0, Short.MAX_VALUE)
            );
            p2Layout.setVerticalGroup(
                p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 56, Short.MAX_VALUE)
            );
    
            p3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            p3.setName("p3"); // NOI18N
    
            tArea.setColumns(20);
            tArea.setRows(5);
            tArea.setWrapStyleWord(true);
            tArea.setBorder(null);
            sP.setViewportView(tArea);
    
            javax.swing.GroupLayout p3Layout = new javax.swing.GroupLayout(p3);
            p3.setLayout(p3Layout);
            p3Layout.setHorizontalGroup(
                p3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(sP, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
            );
            p3Layout.setVerticalGroup(
                p3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(sP, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
            );
    
            p4.setName("p4"); // NOI18N
    
            btn1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            btn1.setText("Enter");
            btn1.setName("btn1"); // NOI18N
            btn1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn1ActionPerformed(evt);
                }
            });
    
            btn2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            btn2.setText("Run Report");
            btn2.setName("btn2"); // NOI18N
            btn2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn2ActionPerformed(evt);
                }
            });
    
            btn3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            btn3.setText("Clear");
            btn3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn3ActionPerformed(evt);
                }
            });
    
            btn4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            btn4.setText("Quit");
            btn4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btn4ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout p4Layout = new javax.swing.GroupLayout(p4);
            p4.setLayout(p4Layout);
            p4Layout.setHorizontalGroup(
                p4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(p4Layout.createSequentialGroup()
                    .addGroup(p4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(p4Layout.createSequentialGroup()
                            .addGap(22, 22, 22)
                            .addComponent(btn1))
                        .addGroup(p4Layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(btn2))
                        .addGroup(p4Layout.createSequentialGroup()
                            .addGap(19, 19, 19)
                            .addGroup(p4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(btn3)
                                .addComponent(btn4))))
                    .addContainerGap(45, Short.MAX_VALUE))
            );
            p4Layout.setVerticalGroup(
                p4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(p4Layout.createSequentialGroup()
                    .addGap(32, 32, 32)
                    .addComponent(btn1)
                    .addGap(28, 28, 28)
                    .addComponent(btn2)
                    .addGap(26, 26, 26)
                    .addComponent(btn3)
                    .addGap(31, 31, 31)
                    .addComponent(btn4)
                    .addContainerGap(31, Short.MAX_VALUE))
            );
    
            lbl2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
            lbl2.setText("Payment for sessions in dollars and cents");
            lbl2.setName("lbl2"); // NOI18N
    
            tBox2.setName("tBox2"); // NOI18N
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lbl2)
                            .addGap(18, 18, 18)
                            .addComponent(tBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(150, 150, 150)
                            .addComponent(p2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGap(213, 213, 213))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(p3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(61, 61, 61)
                            .addComponent(p4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addComponent(p1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(p1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lbl2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(tBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                            .addComponent(p2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(p4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(p3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>                        
    
        private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
                 
            //test to make sure the user is not inputting data for a sixth 
            // session            
            try {
                  if (sessionRows > 5){
                     JOptionPane.showMessageDialog(null, "You are only allow 5 sessions per Report. Please exit and start a new Report.");
                     }
                } catch (Exception e) {
                    this.btn1.setEnabled(false);
                }
            
            try {                    
                //Gather user input for session time and session earnings and assign
                //to variables
                String sessionT = tBox1.getText();
                String wage = tBox2.getText();
                
                double sessionMinutes = Double.parseDouble(sessionT);
                double sessionEarnings = Double.parseDouble(wage);
                
                //Store the variable values in the data array
                data[sessionRows][0] = sessionMinutes;
                data[sessionRows][1] = sessionEarnings;
                sessionRows++;
                
                //clear JTextFields            
                tBox1.setText("");
                tBox2.setText("");                      
                
                //Conditions used to handle invalid inputs
                if (sessionMinutes <= 0){
                    throw new Exception();
                }
                if (sessionMinutes > 240){
                    throw new Exception();
                }
                if (sessionEarnings <= 0){
                    throw new Exception();
                }
            } catch (Exception e) {
                //e.printStackTrace();
                JOptionPane.showMessageDialog(null, "Invalid input. Please try again.");
                sessionRows--;
                data[sessionRows][0] = 0;
                data[sessionRows][1] = 0;
            }   
                        
        }                                    
    
        private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
           
            //Performing the required calculations for the report
            getMinTotal();
            getEarnTotal();
            getAvgWage();
            performAnalysis();
            printArray();
            
            //declaring and initializing the StringBuilders
            StringBuilder sb1 = new StringBuilder(ast + ast + ast + newline);
            StringBuilder sb2 = new StringBuilder(ast + ast + ast + newline + newline);
            
            //Constructing the desired output for the JTextArea
            sb1.append(statement1 + newline);
            sb1.append(newline + prtData + newline);
                    
            sb2.append(statement2 + newline + newline + statement3 + tab + totalMin);
            sb2.append(newline + statement4 + tab + dollar + totalEarn + newline);
            sb2.append(statement5 + tab + dollar + avgWage + newline + newline);
            sb2.append(statement6 + tab + dollar + minWage + newline + newline);
            sb2.append(statement7 + result + period);
            
            //converting the StringBuilders into the required String datatype
            sb1S = sb1.toString();
            sb2S = sb2.toString();
            
           //initializing the text area message variable and setting it to the tArea
            areaMessage = sb1S + newline + sb2S;
            tArea.setText(areaMessage);
    
        }                                    
    
        private void btn3ActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // Clears the contents of the Text Area
            tArea.setText("");
        }                                    
    
        private void btn4ActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // Closes the application out
            System.exit(0);
        }                                    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]){
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(TutorEarnings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(TutorEarnings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(TutorEarnings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(TutorEarnings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new TutorEarnings().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton btn1;
        private javax.swing.JButton btn2;
        private javax.swing.JButton btn3;
        private javax.swing.JButton btn4;
        private javax.swing.JLabel lbl1;
        private javax.swing.JLabel lbl2;
        private javax.swing.JPanel p1;
        private javax.swing.JPanel p2;
        private javax.swing.JPanel p3;
        private javax.swing.JPanel p4;
        private javax.swing.JScrollPane sP;
        private javax.swing.JTextArea tArea;
        private javax.swing.JTextField tBox1;
        private javax.swing.JTextField tBox2;
        // End of variables declaration                   
    }

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,617
    Rep Power
    5

    Default Re: Printing the contents of my Array

    Ok. Try this:

    Java Code:
    public  String printArray(){
            String prtData = "";
            for (int r=0; r < data.length; r++)
            {
                for (int c = 0; c < data[r].length; c++){
                    System.out.printf("%8.2f\n", data[r][c]);              
                    prtData += Double.toString(data[r][c]);
                }
            }
             return prtData;
        }
    Note: I initialized the prtData to a an empty string (""). Before it was just an empty String object or (null).
    I also fixed the the print statement as you were mixing up println and printf syntax.
    Finally, I noticed in your call to printArray that you aren't using the returned value. You need something like this:

    Java Code:
    String prtValue = printArray();
    System.out.println(prtValue);
    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    dalythe is offline Member
    Join Date
    Mar 2013
    Posts
    27
    Rep Power
    0

    Default Re: Printing the contents of my Array

    After making the following changes:

    Java Code:
    public String printArray(){
            for (int r=0; r < data.length; r++)
            {
                for (int c = 0; c < data[r].length; c++){
                    System.out.printf("%8.2f\n", data[r][c]);             
                    prtData += Double.toString(data[r][c]);
             }
            }
             return prtData;
        }
    
    private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
           
            //Performing the required calculations for the report
            getMinTotal();
            getEarnTotal();
            getAvgWage();
            performAnalysis();
            prtData = printArray();
            
            //declaring and initializing the StringBuilders
            StringBuilder sb1 = new StringBuilder(ast + ast + ast + newline);
            StringBuilder sb2 = new StringBuilder(ast + ast + ast + newline + newline);
            
            //Constructing the desired output for the JTextArea
            sb1.append(statement1 + newline);
            sb1.append(newline + prtData + newline);
                    
            sb2.append(statement2 + newline + newline + statement3 + tab + totalMin);
            sb2.append(newline + statement4 + tab + dollar + totalEarn + newline);
            sb2.append(statement5 + tab + dollar + avgWage + newline + newline);
            sb2.append(statement6 + tab + dollar + minWage + newline + newline);
            sb2.append(statement7 + result + period);
            
            //converting the StringBuilders into the required String datatype
            sb1S = sb1.toString();
            sb2S = sb2.toString();
            
           //initializing the text area message variable and setting it to the tArea
            areaMessage = sb1S + newline + sb2S;
            tArea.setText(areaMessage);
    
        }
    I get this output:

    ************************************************** *
    Raw Tutoring Earnings Data

    123.025.0145.025.0178.035.0185.035.0200.040.0

    ************************************************** *

    Report of your wages to Date:

    Total Minutes Spent Tutoring = 831.0
    Total Earnings = $40.0
    Average Per Hour Wage = $2.89

    Minimum Wage is currently = $7.25

    Your average wages per hour are below average.


    It's like it is not accepting my format parameters. Also my column totals for the earnings column ([r][1]) is not getting the right totals and that was working.

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

    Default Re: Printing the contents of my Array

    Where are you using format specifiers in the code above, other than in the printf statement (which shouldn't have \n present but rather should have %n for new lines)?

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,617
    Rep Power
    5

    Default Re: Printing the contents of my Array

    That was my printf statement. I still have a hard time remembering to use the %n since \n works, and has always worked on Unix and Windows (can't remember about Linux) Also, the JDK doesn't throw an IllegalFormat exception of any kind when specifying it this way. Nor is it flagged as an error when placed in strings (unlike other backslashed characters). But on the other hand, if you stick a %n in a regular old println statement, it prints %n!

    Regards,
    Jim
    Last edited by jim829; 03-19-2013 at 01:06 AM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    dalythe is offline Member
    Join Date
    Mar 2013
    Posts
    27
    Rep Power
    0

    Default Re: Printing the contents of my Array

    So I am assuming I have to format the contents in the variable?

Similar Threads

  1. Reading .txt contents and printing them to java GUI
    By hinkey1 in forum AWT / Swing
    Replies: 1
    Last Post: 09-30-2012, 06:41 AM
  2. printing problem of all contents of a canvas
    By mitra in forum Advanced Java
    Replies: 0
    Last Post: 08-05-2011, 08:24 AM
  3. Replies: 19
    Last Post: 08-10-2010, 08:36 AM
  4. Printing the contents of an array of objects
    By Mr.Paplu in forum New To Java
    Replies: 1
    Last Post: 03-19-2009, 04:49 PM
  5. Printing contents of a web page
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-26-2007, 12:37 PM

Posting Permissions

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