Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Simple program with errors

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    31
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Simple program with errors

    Here is my code
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package payroll;
    /**
     *
     * @author SUSER2
     */
    public class pay extends javax.swing.JFrame {
     
        /**
         * Creates new form pay
         */
        public pay() {
            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() {
     
            name = new javax.swing.JLabel();
            hours = new javax.swing.JLabel();
            wage = new javax.swing.JLabel();
            calculate = new javax.swing.JButton();
            clear = new javax.swing.JButton();
            nameInput = new javax.swing.JTextField();
            hourInput = new javax.swing.JTextField();
            wageInput = new javax.swing.JTextField();
            resultTextField = new javax.swing.JTextField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            name.setText("Name: ");
     
            hours.setText("How many hours did you work: ");
     
            wage.setText("What is your hourly wage: ");
     
            calculate.setText("Calculate");
            calculate.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    calculateActionPerformed(evt);
                }
            });
     
            clear.setText("Clear");
            clear.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearActionPerformed(evt);
                }
            });
     
            resultTextField.setEditable(false);
     
            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, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(name)
                            .addGap(138, 138, 138)
                            .addComponent(nameInput, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(hours)
                                .addComponent(wage))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(resultTextField)
                                .addComponent(hourInput)
                                .addComponent(wageInput))))
                    .addContainerGap(88, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(28, 28, 28)
                    .addComponent(calculate)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(clear)
                    .addGap(28, 28, 28))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(50, 50, 50)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(name)
                        .addComponent(nameInput, 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.BASELINE)
                        .addComponent(hours)
                        .addComponent(hourInput, 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.BASELINE)
                        .addComponent(wage)
                        .addComponent(wageInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(40, 40, 40)
                    .addComponent(resultTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(calculate)
                        .addComponent(clear))
                    .addGap(31, 31, 31))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void clearActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        }                                     
     
        private void calculateActionPerformed(java.awt.event.ActionEvent evt) {                                          
     
            double othours, totalpay, pay, otwage, otpay;
     
     
     
            String num1Str = hourInput.getText();
            String num2Str = wageInput.getText();
            String totalpayStr;
     
            double num1 = Double.parseDouble(num1Str);
            double num2 = Double.parseDouble(num2Str);        
     
            if (num1 <= 40) {
                totalpay = num1 * num2;
     
            } if (40 < num1) {
                pay = num1 * num2;
                othours = 40 - num1;
                otwage = num2 * 1.5;
                otpay = otwage * othours;
                totalpay = otpay + pay;
            } 
     
            double result = totalpay;
            String resultStr = Double.toString(result);
     
            resultTextField.setText(resultStr);
        }                                         
     
        /**
         * @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(pay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(pay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(pay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(pay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new pay().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton calculate;
        private javax.swing.JButton clear;
        private javax.swing.JTextField hourInput;
        private javax.swing.JLabel hours;
        private javax.swing.JLabel name;
        private javax.swing.JTextField nameInput;
        private javax.swing.JTextField resultTextField;
        private javax.swing.JLabel wage;
        private javax.swing.JTextField wageInput;
        // End of variables declaration                   
    }

    Error message

    Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - variable totalpay might not have been initialized
    at payroll.pay.calculateActionPerformed(pay.java:145)
    at payroll.pay.access$000(pay.java:10)
    at payroll.pay$1.actionPerformed(pay.java:49)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6290)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:605 5)
    at java.awt.Container.processEvent(Container.java:203 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4653)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2097)
    at java.awt.Component.dispatchEvent(Component.java:44 81)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4575)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4236)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4166)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2083)
    at java.awt.Window.dispatchEventImpl(Window.java:2489 )
    at java.awt.Component.dispatchEvent(Component.java:44 81)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:648)
    at java.awt.EventQueue.access$000(EventQueue.java:84)
    at java.awt.EventQueue$1.run(EventQueue.java:607)
    at java.awt.EventQueue$1.run(EventQueue.java:605)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:621)
    at java.awt.EventQueue$2.run(EventQueue.java:619)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 618)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)
    BUILD SUCCESSFUL (total time: 23 seconds)


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Simple program with errors

    Quote Originally Posted by mstratmann
    Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - variable totalpay might not have been initialized

    You have the following logic structure:
            if (num1 <= 40) {
                // Assign a value to totalpay
            } if (40 < num1) {
                // Assign a different value to totalpay
            }

    Now, we brilliant humans can see immediately what you have in mind, but the compiler just takes things one at a time. It doesn't always get the big picture.

    Now here's the thing:
    You have over-specified the logic conditions since, if num1 is not less than or equal to 40 it must be that 40 is less than num1, right?

    Well, the compiler doesn't see it that way. Regardless of your creative indentation, these are two separate if(){} statements. The compiler only looks at one at a time, and doesn't keep track of whether the second one is related to the first.

    One way that the compiler might like better (with an extra comment that reminds us mere humans what the logic is)
            if (num1 <= 40) {
                // Assign a value to totalpay
            } else { // num1 is not <= 40, so it must be > 40
                // Assign a different value to totalpay
            }

    Now, this is only one if statement, and the compiler knows (since I used else) that it is guaranteed that something will be assigned to totalpay.

    In general, instead of having two separate if statements,where one condition is the logical inverse of the other, use a single if(){}else(){} statement.


    If you really don't want to change the logic to something like I showed, you could just initialize the value of totalpay to something when you declare it. That eliminates that pesky compile-time error, but sometimes defensive programming habits (assigning a value in a declaration statement just for the heck of it) might actually hide some logical error in the program that could end up being hard to debug.



    Cheers!

    Z
    Last edited by Zaphod_b; September 29th, 2012 at 04:55 PM.

  3. The Following 2 Users Say Thank You to Zaphod_b For This Useful Post:

    curmudgeon (September 30th, 2012), mstratmann (April 30th, 2013)

  4. #3
    Member
    Join Date
    Sep 2012
    Posts
    31
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Simple program with errors

    Thanks for the help I was finally able to finish debugging my code and now I can move on with the programming. I was wondering how would I go about connecting my programs to a database?

Similar Threads

  1. Replies: 3
    Last Post: March 6th, 2012, 03:50 AM
  2. [SOLVED] Could someone help me find my errors on this program?? (homework)
    By r19ecua in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 20th, 2011, 11:25 PM
  3. Replies: 3
    Last Post: February 23rd, 2011, 01:27 AM
  4. My program doesnt want to do its math point my errors out please
    By Redlight in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 31st, 2010, 02:56 PM
  5. urgent simple help for a very simple program
    By albukhari87 in forum Java Applets
    Replies: 4
    Last Post: June 5th, 2010, 04:43 PM