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 4 of 4

Thread: Help with JFrame program that calculates average

  1. #1
    Junior Member
    Join Date
    Nov 2011
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Help with JFrame program that calculates average

    Hi everyone. I have a program i'm working on for an assignment that is pretty basic but i still can't get it to work, i'm still really new to Java. This program along with a few others are already way overdue so any quick help would be greatly appreciated.

    The program is a JFrame program that reads three values from the user and then calculates the average value. It has to be formatted so that the output average contains two decimals and the user can input the decimals using either a comma or a dot and it should work either way. Here is the code i have so far:

    package MOM1;
     
    import java.text.DecimalFormat;
     
    public class Average extends javax.swing.JFrame {
     
        /** Creates new form Average */
        public Average() {
            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() {
     
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jTextField3 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jTextFieldAverage = new javax.swing.JTextField();
            jLabel4 = new javax.swing.JLabel();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setBackground(new java.awt.Color(153, 255, 255));
     
            jButton1.setText("Räkna ut");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
            jLabel1.setText("Tal 1");
     
            jLabel2.setText("Tal 2");
     
            jLabel3.setText("Tal 3");
     
            jLabel4.setText("Medelvärde:");
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(47, 47, 47)
                            .addComponent(jLabel1)
                            .addGap(103, 103, 103)
                            .addComponent(jLabel2)
                            .addGap(93, 93, 93)
                            .addComponent(jLabel3))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(152, 152, 152)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(130, 130, 130)
                            .addComponent(jTextFieldAverage, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
                .addGroup(layout.createSequentialGroup()
                    .addGap(29, 29, 29)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(62, 62, 62)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(40, 40, 40))
                .addGroup(layout.createSequentialGroup()
                    .addGap(109, 109, 109)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(127, 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()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(28, 28, 28)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGap(18, 18, 18)
                    .addComponent(jLabel4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jTextFieldAverage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        /* Reads input from the three fields, parses them from
         * string to double and saves them in variables of type
         * double.
         */
     
        DecimalFormat df1=new DecimalFormat("##.00");
     
        String talet1 = null;
        String talet2 = null;
        String talet3 = null;
        double tal1;
        double tal2;
        double tal3;
        double medel;
     
        if (jTextField1.getText().contains(","))
        {
            talet1=jTextField1.getText().replace(',', '.');
        }
        else
        {
            talet1=jTextField1.getText();
        }
     
     
        if (jTextField2.getText().contains(","))
        {
            talet2=jTextField2.getText().replace(',', '.');
        }
        else
        {
            talet2=jTextField2.getText();
        }
     
     
        if (jTextField3.getText().contains(","))
        {
            talet3=jTextField3.getText().replace(',', '.');
        }
        else
        {
            talet3=jTextField3.getText();
        }
     
        tal1 = Double.parseDouble(talet1);
        tal2 = Double.parseDouble(talet2);
        tal3 = Double.parseDouble(talet3);
        medel = (tal1 + tal2 + tal3)/3;
        String svar = DecimalFormat.getInstance().format(medel);
        jTextFieldAverage.setText(df1.format(svar));
    }                                        
     
        /**
         * @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(Average.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Average.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Average.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Average.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 Average().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField jTextField3;
        private javax.swing.JTextField jTextFieldAverage;
        // End of variables declaration                   
    }

    And these are the errors i get whenever i press the calculate button:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1008)
    	at java.lang.Double.parseDouble(Double.java:540)
    	at MOM1.Average.jButton1ActionPerformed(Average.java:121)
    	at MOM1.Average.access$000(Average.java:5)
    	at MOM1.Average$1.actionPerformed(Average.java:37)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    	at java.awt.Component.processMouseEvent(Component.java:6504)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    	at java.awt.Component.processEvent(Component.java:6269)
    	at java.awt.Container.processEvent(Container.java:2229)
    	at java.awt.Component.dispatchEventImpl(Component.java:4860)
    	at java.awt.Container.dispatchEventImpl(Container.java:2287)
    	at java.awt.Component.dispatchEvent(Component.java:4686)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    	at java.awt.Container.dispatchEventImpl(Container.java:2273)
    	at java.awt.Window.dispatchEventImpl(Window.java:2713)
    	at java.awt.Component.dispatchEvent(Component.java:4686)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
    	at java.awt.EventQueue.access$000(EventQueue.java:101)
    	at java.awt.EventQueue$3.run(EventQueue.java:666)
    	at java.awt.EventQueue$3.run(EventQueue.java:664)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    	at java.awt.EventQueue$4.run(EventQueue.java:680)
    	at java.awt.EventQueue$4.run(EventQueue.java:678)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

    What am i doing wrong and how can i fix it?


  2. #2
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: Help with JFrame program that calculates average

    Decimal format code:

    double d = 1.234567;
     DecimalFormat df = new DecimalFormat("#.##");
     System.out.print(df.format(d));

    Source: http://www.javaprogrammingforums.com...al-places.html

    Maybe if your trying to format multiple variables as different formats create multiple format lines?

  3. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Help with JFrame program that calculates average

    at MOM1.Average.jButton1ActionPerformed(Average.java: 121)

    Something on line 121 is null. Find out what is null. Find out why it is null. Make sure it is not null.
    Improving the world one idiot at a time!

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Help with JFrame program that calculates average

    Quote Originally Posted by macko View Post
    Decimal format code:
    ....
    Maybe if your trying to format multiple variables as different formats create multiple format lines?
    What does this have to do with a NullPointerException?

Similar Threads

  1. Moving Average
    By Donieob in forum What's Wrong With My Code?
    Replies: 0
    Last Post: September 3rd, 2011, 08:58 AM
  2. Basic program which gets cost, adds tax, gets payment then calculates change.
    By bibboorton in forum What's Wrong With My Code?
    Replies: 6
    Last Post: August 25th, 2010, 10:31 AM
  3. Moving average
    By bondage in forum Loops & Control Statements
    Replies: 0
    Last Post: May 7th, 2010, 04:20 AM
  4. Imitating a JFrame extended program with JPanel; help needed...
    By emigrant in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 15th, 2010, 02:30 PM
  5. Average program with array and loop and JOptionPane.
    By jeremykatz in forum AWT / Java Swing
    Replies: 6
    Last Post: October 25th, 2009, 02:33 PM

Tags for this Thread