3 Replies - 2939 Views - Last Post: 02 October 2011 - 07:00 AM Rate Topic: -----

#1 bramills  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 26-September 11

Sum 2d Array - outputs incorrect - I need an assist

Posted 02 October 2011 - 06:20 AM

I hope someone can give me another eye on this code because I am not sure I can fix it.

I am working on homework assignment which calls to sum a 2d array using nested for loop. I believe I have completed this portion of the task; however, my output is not correct.

I need an assist.

Input:
Minutes= 100.0 Earnings= 500.0
Minutes= 100.0 Earnings= 500.0
Minutes= 100.0 Earnings= 500.0
Minutes= 100.0 Earnings= 500.0


Output:
Minutes= 100.0 Earnings= 500.0
Minutes= 100.0 Earnings= 500.0
Minutes= 100.0 Earnings= 500.0
Minutes= 100.0 Earnings= 500.0
****************************************************
Raw Tutoring Earnings Data

Minutes Earnings
100.0 500.0
100.0 500.0
****************************************************

Report of your wages to Date:
____________________________

Total Minutes Spent Tutoring = 600.0
Total Earnings = $600.0
Average Per Hour Wage = $300.0
Effective July 24, 2009, the federal minimum wage is set to = $7.55 per hour
Your average wages per hour are Above Average


I am storing the correct data on the original array, but not on the nested for loop. Also the sum of the total minutes is not 600.0 it should be 400.0 and the total earned should be 2000.0 but it is also 600.0.

I have messed it up. I apologize for the GUI autocode, but I was also required to use the GUI builder and I also apologize for not commenting my code as I am trying to crawl before I walk with JAVA. you can yell at me if you feel the need.Attached File  tutCalc.zip (36.36K)
Number of downloads: 138 Here is the code:

Main:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Brandi's Laptop
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        javax.swing.JFrame myFrame = new javax.swing.JFrame();
        myFrame.add(new GUI());
        myFrame.setTitle("Tutoring Calculator");
        myFrame.setSize(500, 500);
        myFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        myFrame.setVisible(true);
        
        // TODO code application logic here
    }
}






GUI:


import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * samplepanel.java
 *
 * Created on Sep 27, 2011, 8:12:34 PM
 */
/**
 *
 * @author Brandi's Laptop
 */
public class GUI extends javax.swing.JPanel {

    double[][] array = new double[10][2];
    int index = 0;
    double tutMins = 0;
    double earnings = 0;
    static final String lineSeparator = System.getProperty("line.separator");

    /** Creates new form GUI */
    public GUI() {
        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() {

        tutMinsLabel = new javax.swing.JLabel();
        earningsLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        reportTextArea = new javax.swing.JTextArea();
        tutMinsText = new javax.swing.JTextField();
        earningsText = new javax.swing.JTextField();
        enterButton = new javax.swing.JButton();
        reportButton = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();

        tutMinsLabel.setText("Enter total tutoring time in minutes:");

        earningsLabel.setText("Enter total amount earned this session:");

        reportTextArea.setColumns(20);
        reportTextArea.setRows(5);
        jScrollPane1.setViewportView(reportTextArea);

        enterButton.setText("Enter");
        enterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enterButtonActionPerformed(evt);
            }
        });

        reportButton.setText("Report");
        reportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reportButtonActionPerformed(evt);
            }
        });

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

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(enterButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(reportButton, 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)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(tutMinsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(earningsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(earningsText)
                            .addComponent(tutMinsText, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))))
                .addContainerGap(58, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(tutMinsText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(tutMinsLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(earningsLabel)
                    .addComponent(earningsText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(enterButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(reportButton)
                        .addGap(18, 18, 18)
                        .addComponent(quitButton)
                        .addContainerGap(320, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)))
        );
    }// </editor-fold>

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


        //Code Exception error messages when data keyed incorrectly for both textfields
        try {
            tutMins = Double.parseDouble(
                    this.tutMinsText.getText());
            if (tutMins <= 0 || tutMins > 240) {
                throw new Exception();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Invalid input. Minutes can't be less than 0 or more than 240. Please try again",
                    "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            earnings = Double.parseDouble(
                    this.earningsText.getText());
            if (earnings <= 0) {
                throw new Exception();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Invalid input. Earnings must be greater than zero. Please try again", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        array[index][0] = tutMins;
        array[index][1] = earnings;
        String message = "";

        for (int i = 0; i <= index; i++) {

            message += "Minutes=  " + array[i][0] + " " + "Earnings= " + array[i][1] + "\n";
            reportTextArea.setText(message);

        }

        this.tutMinsText.setText("");
        this.earningsText.setText("");

        index++;


    }                                           

    private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        //select to close the Calculator
        System.exit(0);

    }                                          

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

        int cols = 2;
        int rows = array[0].length;
        double timeSpentTotal = 0.00;
        double earningsTotal = 0.00;
        double averageWage = 0.00;
        double minimumWage = 7.55;
        String report = new String();

        report += "****************************************************\n\n";
        report += "Raw Tutoring Earnings Data\n\n";
        report += "\n";
        report += "Minutes      Earnings\n";

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                report += array[i][j];
                report += "           ";

                if (i == 0) {
                    timeSpentTotal += array[i][j];
                } else if (i == 1) {
                    earningsTotal += array[i][j];
                }
            }

            report += "\n";
        }

        if (array[0].length > 0) {
            averageWage = earningsTotal / array[0].length;
        }

        report += "****************************************************\n\n";
        report += "Report of your wages to Date:\n";
        report += "____________________________\n\n";
        report += "Total Minutes Spent Tutoring = " + timeSpentTotal + "\n";
        report += "Total Earnings = $" + earningsTotal + "\n";
        report += "Average Per Hour Wage = $" + averageWage + "\n";
        report += "Effective July 24, 2009, the federal minimum wage is set to = $" + minimumWage + " per hour" + "\n";

        report += "Your average wages per hour are ";

        if (averageWage < minimumWage) {
            report += "Below Average";
        } else if (averageWage >= minimumWage && averageWage <= minimumWage * 2.00) {
            report += "Average";
        } else if (averageWage > minimumWage * 2.00) {
            report += "Above Average";
        }

        reportTextArea.append(report);
    }                                            
    // Variables declaration - do not modify
    private javax.swing.JLabel earningsLabel;
    private javax.swing.JTextField earningsText;
    private javax.swing.JButton enterButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton quitButton;
    private javax.swing.JButton reportButton;
    private javax.swing.JTextArea reportTextArea;
    private javax.swing.JLabel tutMinsLabel;
    private javax.swing.JTextField tutMinsText;
    // End of variables declaration
}




Is This A Good Question/Topic? 0
  • +

Replies To: Sum 2d Array - outputs incorrect - I need an assist

#2 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: Sum 2d Array - outputs incorrect - I need an assist

Posted 02 October 2011 - 06:39 AM

The problem is with this nested loop here:
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                report += array[i][j];
                report += "           ";

                if (i == 0) {
                    timeSpentTotal += array[i][j];
                } else if (i == 1) {
                    earningsTotal += array[i][j];
                }
            }

            report += "\n";
        }

Remember how you were saving your data:
         array[index][0] = tutMins;
        array[index][1] = earnings;


all minutes were in column 0 and all earnings were at column 1, so there is no need for nested loop there. Also row will always be 2. This is not true int rows = array[0].length; it should be int rows = array.length;.

So the loop was going twice and adding 500 + 100 for every case in your if condition, that is why we have 600.
Simply your code should be:
for (int i = 0; i < rows; i++) { //remeber to change how we gate rows
   timeSpentTotal += array[i][0];
   earningsTotal += array[i][1];
adding other of your issues and ready to go
Was This Post Helpful? 1
  • +
  • -

#3 bramills  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 26-September 11

Re: Sum 2d Array - outputs incorrect - I need an assist

Posted 02 October 2011 - 06:56 AM

You know quietly on the inside I was hoping this was not my issue. The rubric requires I have a for Nested loop...

ie. Implement the “Run Report” button to iterate through the two-dimensional array using a nested for-loop to display the earnings data to the jTextArea, as illustrated in the attached “Earnings Entered.”

So I am actually looking at changing the way I gather the data to begin with, right?
Was This Post Helpful? 0
  • +
  • -

#4 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: Sum 2d Array - outputs incorrect - I need an assist

Posted 02 October 2011 - 07:00 AM

Yap, if that is required, then change;
        if (i == 0) {
            timeSpentTotal += array[i][j];
        } else if (i == 1) {
            earningsTotal += array[i][j];
        }

to
  if (j == 0) { //change to j becuase it is the one to be tested
            timeSpentTotal += array[i][j];
        } else if (j == 1) {
            earningsTotal += array[i][j];
        }

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1