Results 1 to 5 of 5
  1. #1
    scottdaking is offline Member
    Join Date
    Feb 2013
    Location
    Baltimore, MD
    Posts
    10
    Rep Power
    0

    Default Getting minimum value from an array

    So, I got some much needed assistance through another thread (thanks so much), and I actually got most of this program working properly. The last issue I can't seem to code correctly is determining the minimum wage value from the array inputs. I have two primary methods for the user input and to run a report. Although the instructions indicate the minimum wage should be displayed when the report method is run, I figured it would make more sense to determine the minimum wage in the input method. I'm still trying to get the hang of the logic, so...can anyone clue me in on how (and where) to get the minimum values from this array? Here's the code:


    Java Code:
    import java.awt.Component;
    import javax.swing.JOptionPane;
    
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author King
     */
    public class TutorUI extends javax.swing.JFrame {
    
        double[][] tutorArray = new double [20][2];
        int i = 0;
        double totalMinutes = 0;
        double totalHours = 0;
        double totalWages = 0;
        double averageWage = 0;
        double minimumWage = 0;
        /**
         * Creates new form TutorUI
         */
        public TutorUI() {
            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() {
    
            jPanel1 = new javax.swing.JPanel();
            sessionLabel = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            dataTextArea = new javax.swing.JTextArea();
            earningsLabel = new javax.swing.JLabel();
            sessionLength = new javax.swing.JTextField();
            earningsReceived = new javax.swing.JTextField();
            enterButton = new javax.swing.JButton();
            runReportButton = new javax.swing.JButton();
            quitButton = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            sessionLabel.setText("Enter length of session in seconds:");
    
            dataTextArea.setColumns(20);
            dataTextArea.setRows(5);
            jScrollPane1.setViewportView(dataTextArea);
    
            earningsLabel.setText("Enter how much received in dollars and cents:");
    
            sessionLength.setText("Session Length");
            sessionLength.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sessionLengthActionPerformed(evt);
                }
            });
    
            earningsReceived.setText("Earnings Received");
            earningsReceived.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    earningsReceivedActionPerformed(evt);
                }
            });
    
            enterButton.setText("Enter");
            enterButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    enterButtonActionPerformed(evt);
                }
            });
    
            runReportButton.setText("Run Report");
            runReportButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    runReportButtonActionPerformed(evt);
                }
            });
    
            quitButton.setText("Quit");
            quitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quitButtonActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(68, 68, 68)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(runReportButton)
                                .addComponent(quitButton)
                                .addComponent(enterButton))
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(sessionLabel)
                                .addComponent(earningsLabel))
                            .addGap(18, 18, 18)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(0, 0, Short.MAX_VALUE)
                                    .addComponent(sessionLength, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(earningsReceived)))))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap(14, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(sessionLabel)
                        .addComponent(sessionLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(earningsLabel)
                        .addComponent(earningsReceived, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addComponent(enterButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(runReportButton)
                            .addGap(31, 31, 31)
                            .addComponent(quitButton)))
                    .addContainerGap(49, Short.MAX_VALUE))
            );
    
            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()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(30, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(14, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(15, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void sessionLengthActionPerformed(java.awt.event.ActionEvent evt) {                                              
            // TODO add your handling code here:
        }                                             
    
        private void earningsReceivedActionPerformed(java.awt.event.ActionEvent evt) {                                                 
            // TODO add your handling code here:
        }                                                
    
        private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
            double time = Double.parseDouble(sessionLength.getText());
            double earnings = Double.parseDouble(earningsReceived.getText());
            //each time user enters the time spent and earnings received for each
            //tutor session, those values will be added to the array.
            
            //positive input warning
            if (time <= 0 || earnings <= 0) {
                Component frame = null;
                JOptionPane.showMessageDialog(frame,"Values for time and earnings must be positive numbers", "Invalid Input Warning", JOptionPane.WARNING_MESSAGE);
            }
            else {
                tutorArray[i][0] = time;
                tutorArray[i][1] = earnings;
                 
                totalMinutes += time;
                totalWages += earnings;
            
             //display time and earnings so far
             dataTextArea.append("Minutes =" + " " + time + "      " + "Earnings = $" + earnings + "\n");
             
             i++;
            }
            
        }                                           
    
        private void runReportButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
            // TODO add your handling code here:
                  
            //determine the minimum wage   
            for (int s = 0; s < tutorArray.length - 1; s++) {
                    //find position of minimum value
                    int minPos = s;
                    for (int t = s + 1; t < tutorArray.length; t++){
                        if (tutorArray [t][1] < tutorArray[s][1]) {
                        minPos = t;
                    }
                    }
            }
            String minPos = null;
            dataTextArea.append("\nThe position of the minimum value is:" + "  " + minPos + "\n");
            //convert total minutes of tutoring to hours
            totalHours = totalMinutes / 60;
            
            //then calculate average wage per hour
            averageWage = totalWages / totalHours;
            
            
            //print report
            dataTextArea.append("\n\n**************************");
            String line;
            line = String.format("\n\nReport of your wages to Date:" + "   " + "%7.2f", totalWages);
            dataTextArea.append(line);
            line = String.format("\n\nTotal Minutes Spent Tutoring =" + "   " + "%7.2f", totalMinutes);
            dataTextArea.append(line);
            line = String.format("\nTotal Earnings =" + "   " + "%7.2f", totalWages);
            dataTextArea.append(line);
            line = String.format("\nAverage Per Hour Wage = $" + "   " + "%7.2f", averageWage);
            dataTextArea.append(line);
                   
            //determine whether average wages per hour are average, above or below average, then print
            
            line = String.format("\n\nMinimum Wage is currently = $" + minimumWage);     
            dataTextArea.append(line);
        }                                               
    
        private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
            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 [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url] 
             */
            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(TutorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(TutorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(TutorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(TutorUI.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 TutorUI().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JTextArea dataTextArea;
        private javax.swing.JLabel earningsLabel;
        private javax.swing.JTextField earningsReceived;
        private javax.swing.JButton enterButton;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JButton quitButton;
        private javax.swing.JButton runReportButton;
        private javax.swing.JLabel sessionLabel;
        private javax.swing.JTextField sessionLength;
        // End of variables declaration
    }
    I'm using NetBeans 7.2.1 and am very appreciative of all of the support!

    Thanks so much,
    Scott

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    8

    Default Re: Getting minimum value from an array

    You can simply loop the array and compare each element of the array and keeping the minimum value in a variables. If you are allowed to use the provided Java API you can check the java.util.Collections class to find the methods in there to get the min or max value of an array.

  3. #3
    scottdaking is offline Member
    Join Date
    Feb 2013
    Location
    Baltimore, MD
    Posts
    10
    Rep Power
    0

    Default Re: Getting minimum value from an array

    Many thanks, wsaryada! You saved me from going bald today! I pulled all but a few hairs out trying to figure this thing out!!!!!

    Scott

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

    Default Re: Getting minimum value from an array

    Java Code:
      //determine the minimum wage          
    
     for (int s = 0; s < tutorArray.length - 1; s++) {
              //find position of minimum value
              int minPos = s;
               for (int t = s + 1; t < tutorArray.length; t++){
                    if (tutorArray [t][1] < tutorArray[s][1]) {
                        minPos = t;
                    }
               }
    }
    String minPos = null;
    dataTextArea.append("\nThe position of the minimum value is:" + "  " + minPos + "\n");
        
    //convert total minutes of tutoring to hours
    I am not certain what you are doing above but first you calculate some value for a minPos. Then when you exit the loop the earlier variable is lost because it is local to the loop. The new minPos is now a null string which you print out.

    If you want to record the index of the smallest value of an array, do it something like this. Assume the values are in an array of doubles.

    Java Code:
    nt minPos = 0;
    double minValue = 100000; // initialize to something larger than minimum value in array (usually a very large number)
    for (int j = 0; j < array.length; j++) {
        if (array[j] < minValue) {
            minValue = array[j];
            minPos = j;
        }
    }
    At the point, minPos will index to the minimum value in array.

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

  5. #5
    scottdaking is offline Member
    Join Date
    Feb 2013
    Location
    Baltimore, MD
    Posts
    10
    Rep Power
    0

    Default Re: Getting minimum value from an array

    Thanks so much, Jim! I appreciate the help, although I've now been instructed that my minimum value is supposed to be a CONSTANT!!!!! I still need to use the loop to calculate totals for two other variables. I LOVE programming, I LOVE programming...

    Scott

Similar Threads

  1. Keeping a minimum value of an array up to date?
    By danboy4 in forum New To Java
    Replies: 0
    Last Post: 10-01-2012, 05:38 AM
  2. Minimum of 2d Array
    By Spyderpig in forum New To Java
    Replies: 8
    Last Post: 03-10-2011, 04:05 PM
  3. [SOLVED] Help Finding the Minimum value of an array
    By MSteinman in forum New To Java
    Replies: 18
    Last Post: 04-21-2009, 09:14 AM
  4. To find the Maximum and Minimum in an Array of Strings
    By luscious in forum JavaServer Pages (JSP) and JSTL
    Replies: 9
    Last Post: 07-31-2008, 01:51 PM
  5. Replies: 1
    Last Post: 02-16-2008, 09:10 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
  •