#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0

    Form Data to 2D Array and Output to Text Area


    Hello! I'm sure you've gotten this request before from some fellow university students. I'm working on an assignment that requires me to store time and earnings data in a two dimensional array. I'm supposed to do some calculations based on the data and then report it back to the user in a text area.

    Because I am very new to Java and the course recommends it, I am using NetBeans for development. I've included the code where a user clicks an 'Input' button. If clicked, the users data in Time and Earnings fields will be stored in a 2d array. If they then enter new data and click 'Input' that second set of data should be stored in the next row in the array, so on and so forth.

    My problem is that I cannot figure out how to tell if my 'Input' click is actually storing the data in the array. How can I best see if what is supposed to happen is actually happening? Please advise, thanks!

    In my public declaration I have the creation of the array:

    //Create Array
    double[][] tutArray = new double[10][2];

    Code:
        private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // Declaring Variables for Tutoring
            double tutMinutes = 0;
            double tutPayment = 0;
            
            // Validation of Entries for Time Worked and Earnings
            try {
                tutMinutes = Double.parseDouble(
                        this.txtTutoringTime.getText());
                if (tutMinutes <=0 || tutMinutes > 240) {
                    throw new Exception();
                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Minutes cannot be less than '0' or more than '240'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            try {
                tutPayment = Double.parseDouble(
                        this.txtPayment.getText());
                if (tutPayment <=0 ) {
                    throw new Exception();
                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Earnings must be more than '0'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // Store Array Values
            for (int i = 0; i < tutArray.length; i++) {
                for (int j = 0; j < tutArray[i].length; j++){
                    tutArray[i][0] = tutMinutes;
                    tutArray[i][1] = tutPayment;
                }
            }      
    
            //Clear Text Fields for Next Entry
            txtTutoringTime.setText("");
            txtPayment.setText("");
            
    
        }
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,724
    Rep Power
    348
    how to tell if my 'Input' click is actually storing the data in the array.
    Use this command to print out the contents of the 2D array on the console:
    System.out.println("an ID "+ java.util.Arrays.deepToString(theArrayName));

    Comments on this post

    • jrennard3 agrees
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0
    Thanks for that line of code! That worked perfectly!

    So, my array is storing data from the two input fields, but it isn't storing it how I intended.

    Instead of storing a single 'row' of the two values, then a second 'row' upon the next input click, it is overwriting all 10 initialized 'rows' with the two values.

    My first entry was 10 and 50, which filled all 10 rows with 10.0, 50.0. The second entry was 10 and 60, which filled all 10 rows with 10.0, 60.0. You can see the output below:

    Code:
    an ID [[10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0], [10.0, 50.0]]
    an ID [[10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0], [10.0, 60.0]]
    How can I format the filling of data to the array so that with each input the two values are stored in a new row of the first array rather than being stored in all spaces of the second array?
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0
    I've modified the code slightly and it is now storing the input fields in the first row of the array, as I would like it to. However, upon clicking input again with a new set of data it is overwriting the first row in the array instead of appending it to the second place in the array.

    How can I tell the button to check if a row of the array is already populated and move to the next row? Thanks for your help!

    java Code:
    public class Ket1Task1 extends javax.swing.JFrame {
     
        /**
         * Creates new form Ket1Task1
         */
        public Ket1Task1() {
            initComponents();
        }
     
        //Create Array
        double[][] tutArray = new double[10][2];
        int i = 0;
     
        private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // Declaring Variables for Tutoring
            double tutMinutes = 0;
            double tutPayment = 0;
            int index = 0;
     
            // Validation of Entries for Time Worked and Earnings
            try {
                tutMinutes = Double.parseDouble(
                        this.txtTutoringTime.getText());
                if (tutMinutes <=0 || tutMinutes > 240) {
                    throw new Exception();
                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Minutes cannot be less than '0' or more than '240'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
            try {
                tutPayment = Double.parseDouble(
                        this.txtPayment.getText());
                if (tutPayment <=0 ) {
                    throw new Exception();
                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Earnings must be more than '0'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
            // Store Array Values
               tutArray[index][0] = tutMinutes;
               tutArray[index][1] = tutPayment;
               index++;
     
            //Clear Text Fields for Next Entry
            txtTutoringTime.setText("");
            txtPayment.setText("");
            System.out.println("an ID "+ java.util.Arrays.deepToString(tutArray));
     
        }
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0
    I'm really sorry for the multiple posts, but maybe this will help someone down the road. I am not sure if this is pure and undefiled Java, but this seems to work, please let me know your thoughts!

    Basically, I moved my index variable to the public class, which allowed it to persist throughout each click of the private button action.

    java Code:
     
    public class Ket1Task1 extends javax.swing.JFrame {
     
        /**
         * Creates new form Ket1Task1
         */
        public Ket1Task1() {
            initComponents();
        }
     
        //Create Array
        double[][] tutArray = new double[10][2];
        int i = 0;
        int index = 0;
     
    private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // Declaring Variables for Tutoring
            double tutMinutes = 0;
            double tutPayment = 0;
     
     
            // Validation of Entries for Time Worked and Earnings
            try {
                tutMinutes = Double.parseDouble(
                        this.txtTutoringTime.getText());
                if (tutMinutes <=0 || tutMinutes > 240) {
                    throw new Exception();
                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Minutes cannot be less than '0' or more than '240'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
            try {
                tutPayment = Double.parseDouble(
                        this.txtPayment.getText());
                if (tutPayment <=0 ) {
                    throw new Exception();
                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Earnings must be more than '0'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
            // Store Array Values
               tutArray[index][0] = tutMinutes;
               tutArray[index][1] = tutPayment;
               index++;
     
            //Clear Text Fields for Next Entry
            txtTutoringTime.setText("");
            txtPayment.setText("");
            System.out.println("an ID "+ java.util.Arrays.deepToString(tutArray));
     
        }
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0
    I'm on to the next section of my program and need to output the data from the array to the jtextarea on my gui. I've figured out how to do this using append and can even get it to spit out the first row of the array, but I am having some issues with looping each row of the array.

    I've tried setting up a nested loop to grab the first array, then display the second array, but since the values are doubles, it will not let it convert to a string.
  12. #7
  13. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,724
    Rep Power
    348
    not let it convert to a string
    Please copy the full text of the error message and paste it here. It has important info about the error.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0
    java Code:
     
    System.out.println("an ID " + java.util.Arrays.deepToString(tutArray));
     
            for (int x = 0; x < ROW; x++){
                for (int y = 0; y < COL; y++){
     
                    txtReportArea.append(tutArray[x][y]);
                }
                txtReportArea.append("\n");
            }


    I was hoping that would get me started and just show each row of the array with the two values in the columns on a new line, but it doesn't. The tooltip says "Incompatible Types: double cannot be converted to string".

    If I remove the [x][y] and add in the 'java.util.Arrays.deepToString' it will spit out the same thing that is currently being spit out to the system window.

    Perhaps I'm approaching this the wrong way entirely, since I don't have to display the array data, just calculate on it. However, I wanted to try to display it first so I knew what to calculate on.

    Essentially, I have two columns:

    Minutes | Payment

    Then I have currently up to 10 rows available for the user to enter in Minute | Payment data.

    I need to calculate the sum of Minutes, the sum of Payment, Average Per Hour Wage, and whether or not the Per hour Wage is above a set minimum wage.

    If I am only calculating based on the array data, should I be accessing the data in some way other than the nested for loop?

    Thanks again for your help!
  16. #9
  17. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,724
    Rep Power
    348
    double cannot be converted to string
    Look at the Double class. It has methods for converting a double to a String.
    Also look at the DecimalFormat class for control of the formatting of the number.

    If the array has two columns with different data, then a single loop will access each row and the code inside the loop can access each of the two columns as needed.
    Last edited by NormR; February 12th, 2014 at 12:52 PM.
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0
    Thanks for the info Norm, I'd love to get some more thoughts on the decimal format especially. As I continue to work on this, I would like to perfect it.

    Here is what I have so far and it seems to be working:

    java Code:
     
    public class Ket1Task1 extends javax.swing.JFrame {
     
        /**
         * Creates new form Ket1Task1
         */
        public Ket1Task1() {
            initComponents();
        }
     
        //Create Array
        final int ROW = 10;
        final int COL = 2;
        double[][] tutArray = new double[ROW][COL];
        int i = 0;
        int index = 0;
     
        private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // Declaring Variables for Tutoring
            double tutMinutes = 0;
            double tutPayment = 0;
     
            // Validation of Entries for Time Worked and Earnings
            try {
                tutMinutes = Double.parseDouble(
                        this.txtTutoringTime.getText());
                if (tutMinutes <= 0 || tutMinutes > 240) {
                    throw new Exception();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Minutes cannot be less than '0' or more than '240'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
            try {
                tutPayment = Double.parseDouble(
                        this.txtPayment.getText());
                if (tutPayment <= 0) {
                    throw new Exception();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "You've entered an incorrect value.  Earnings must be more than '0'.  Please try again!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
     
            // Store Array Values
            tutArray[index][0] = tutMinutes;
            tutArray[index][1] = tutPayment;
            index++;
     
            String txtMinutesVal = Double.toString(tutMinutes);
            String txtPaymentVal = Double.toString(tutPayment);
            txtReportArea.append("Minutes = " + txtMinutesVal + "   " + "Earnings= " + txtPaymentVal);
            txtReportArea.append("\n");
     
            // Clear Text Fields for Next Entry
            txtTutoringTime.setText("");
            txtPayment.setText("");
     
     
        }                                        
     
        private void btnRunReportActionPerformed(java.awt.event.ActionEvent evt) {                                             
            System.out.println("an ID " + java.util.Arrays.deepToString(tutArray));
            // Calculate and store array values for Minutes
            int sizeMin = 2;
            double minutes[] = new double[sizeMin];
     
            for (int x = 0; x < tutArray.length; x++){
                for (int y = 0; y < tutArray[x].length; y++){
                    minutes[y] += tutArray[x][y]; 
     
                }
            }
            String sumMinutes = Double.toString(minutes[0]);
     
            // Payments
            int sizePay = 2;
            double payment[] = new double[sizePay];
     
            for (int x = 0; x < tutArray.length; x++){
                for (int y = 0; y < tutArray[x].length; y++){
                    payment[y] += tutArray[x][y]; 
     
                }
            }
            String sumPayment = Double.toString(payment[1]);
            txtReportArea.append("\n" + "*******************************************" + "\n" + "\n");
            txtReportArea.append("Report of Your Wages to Date:" + "\n" + "\n");
            txtReportArea.append("Total Minutes Spent Tutoring: " + sumMinutes + "\n");
            txtReportArea.append("Total Earnings Receieved:  $" + sumPayment);
     
     
        }


    So far, it is doing everything I need it to do. I need to clean up some code a bit and would like to get the formatting for the payments/earnings to default to two decimal places, but so far so good!

IMN logo majestic logo threadwatch logo seochat tools logo