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

Thread: Rate this code on a scale from 1 - 10 and please suggest some improvements.

  1. #1
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Rate this code on a scale from 1 - 10 and please suggest some improvements.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package GUI;
     
    /**
     *
     * @author REDACTED
     */
    public class CalculatorGUI extends javax.swing.JFrame {
     
        public double firstDouble;
        public double secondDouble;
        public double answer = 0;
        public double yolo = 0;
        boolean operatorIsSelected = false;
        double olo = 0;
        boolean press = false;
        String operators = "";
     
        public static void equals(String[] args) {
        }
     
        /**
         * Creates new form CalculatorGUI
         */
        public CalculatorGUI() {
            initComponents();
            result.setText("");
     
        }
     
        public int numberLength() {
            String numberL = result.getText();
            return numberL.length();
        }
     
        /**
         * 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")
        <!-- code redacted -->    
     
        private void oneActionPerformed(java.awt.event.ActionEvent evt) {                                    
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "1");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "1");
                }
            } else {
                result.setText("1");
            }
     
        }                                   
     
        private void twoActionPerformed(java.awt.event.ActionEvent evt) {                                    
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "2");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "2");
                }
            } else {
                result.setText("2");
            }
        }                                   
     
        private void threeActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "3");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "3");
                }
            } else {
                result.setText("3");
            }
        }                                     
     
        private void fourActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "4");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "4");
                }
            } else {
                result.setText("4");
            }
        }                                    
     
        private void fiveActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // TODO add your handling code here:
             numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "5");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "5");
                }
            } else {
                result.setText("5");
            }
        }                                    
     
        private void sixActionPerformed(java.awt.event.ActionEvent evt) {                                    
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "6");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "6");
                }
            } else {
                result.setText("6");
            }
        }                                   
     
        private void sevenActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "7");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "7");
                }
            } else {
                result.setText("7");
            }
        }                                     
     
        private void eightActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "8");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "8");
                }
            } else {
                result.setText("8");
            }
        }                                     
     
        private void nineActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "9");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "9");
                }
            } else {
                result.setText("9");
            }
        }                                    
     
        private void zeroActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // TODO add your handling code here:
            numberLength();
            if (numberLength() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + "0");
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "0");
                }
            } else {
                result.setText("0");
            }
        }                                    
     
        private void clearAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            result.setText("");
            firstDouble = 0;
            secondDouble = 0;
        }                                        
     
        private void resultActionPerformed(java.awt.event.ActionEvent evt) {                                       
            // TODO add your handling code here:
        }                                      
     
        private void divisionActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("/");
            operatorIsSelected = true;
            operators = "/";
        }                                        
     
        private void multiplicationActionPerformed(java.awt.event.ActionEvent evt) {                                               
            // TODO add your handling code here:
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("X");
            operatorIsSelected = true;
            operators = "*";
        }                                              
     
        private void additionActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("+");
            operatorIsSelected = true;
            operators = "+";
        }                                        
     
        private void subtractionActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("-");
            operatorIsSelected = true;
            operators = "-";
        }                                           
     
        private void equalsActionPerformed(java.awt.event.ActionEvent evt) {                                       
            // TODO add your handling code here:
            secondDouble = Double.parseDouble(result.getText());
     
            switch (operators) {
                case "/":
                    answer = firstDouble / secondDouble;
                    operators = "";
                    break;
                case "*":
                    answer = firstDouble * secondDouble;
                    operators = "";
                    break;
                case "+":
                    answer = firstDouble + secondDouble;
                    operators = "";
                    break;
                case "-":
                    answer = firstDouble - secondDouble;
                    operators = "";
                    break;
            }
     
            result.setText("" + answer + "");
     
        }                                      
     
        /**
         * @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(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.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 CalculatorGUI().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton addition;
        private javax.swing.JButton clear;
        private javax.swing.JButton clearAll;
        private javax.swing.JButton decimal;
        private javax.swing.JButton division;
        private javax.swing.JButton eight;
        private javax.swing.JButton equals;
        private javax.swing.JButton five;
        private javax.swing.JButton four;
        private javax.swing.JButton multiplication;
        private javax.swing.JButton nine;
        private javax.swing.JButton one;
        private javax.swing.JFormattedTextField result;
        private javax.swing.JButton seven;
        private javax.swing.JButton six;
        private javax.swing.JButton subtraction;
        private javax.swing.JButton three;
        private javax.swing.JButton two;
        private javax.swing.JButton zero;
        // End of variables declaration                   
    }

    Obviously there is quite a lot of spaghetti code, am I'm not quite knowledgeable enough with Java to know any alternatives to the problem...


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Some useless comments:
    // TODO add your handling code here:

    And no useful comments about what the code does and why

    Many calls to a method that returns a value without saving the returned value:
       numberLength();
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    This is generated by a gui builder, so I automatically give it a 1. So much messier, so much harder to read, and so much harder to maintain. It's much better to go through the Swing tutorials and write your own gui rather than rely on a gui builder.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    ok

  5. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Use of non-final public fields is generally discouraged, use private field with getters/setters instead.

    There are a variety of fields at the top which utilize default access restrictions, again this is generally discouraged.

    There's a general lack of useful comments and Javadoc.

    for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + "3");
                }
    Eh? What's going on with this code? There are several things bad with this code:

    1. Don't modify the for-loop variable outside the for loop. There's a place for increment/post-iteration code in the for statement for a reason.
    2. It's quite obvious this code only executes once. So why even loop?
    3. You're setting result's text to null, then to some value. Why? There's no need.

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

    numberLength() is returning a value, but you never store it. Either make use of the return result or get rid of that line.

    There are some fields you aren't using, and I can't figure out any obvious use for them. For example, the double fields yolo and olo. Pick a name that makes obvious sense and use the field, or get rid of the fields.

    The GUI builder code isn't great, there are very few out there that I would consider "decent" for larger projects solely because they can handle manual code modifications fairly well (this does not look like it's one of them). For something this simple I would recommend sticking with hand-written code. A big problem this leads to is what I assume is individual action performed event handlers for each button. This results in tons of unnecessary code that's a pain to maintain. Look for a solution which uses a single event handler so you can re-use as much code as possible. This will be much easier/quicker to maintain and likely much easier to read (if written correctly).

    Overall not very good code.

  6. #6
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Ok so yes, the vars olo, yolo and method numberLength() were experiments from previous attempts at getting this code to work. Now I don't understand why should I use getters and setters instead of the code already made? Is it more efficient or what?

    The beauty of this code apart from the fact this is my first attempt at making anything in java from scratch is that it lets you have numbers with infinite digits input into the calculator and still use the answer from that previous calculation as the first number in the second calculation (a feature I didn't intend to make at first). I mean the code works, why is it as if I've committed some sort of programming blasphemy with regards to this code?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    why is it as if I've committed some sort of programming blasphemy
    The code uses lots of poor techniques. It shows lack of experience.

    I haven't studied what it does or how it works, but just looking at it I see many listener methods that are almost identical . When you get more than 2 methods that are the same except for one or two variables, it's time to think of how to make one method that takes some args rather than have so much repeated code.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Getters/setters are preferred because they help to abstract the code design, and give you more precise control over how your class is used/accessed.

    For example, consider the ArrayList class. Internally it makes sense to have a size variable which keeps track of how many elements are actually being used. This should only be modified internally, so the class only provides a getter. What happens if you used a public size field instead? Well, a user could theoretically change the size to whatever size they want, say -1. However, the size should be able to be updated internally. This means you can't have a final size field as that can't be modified anywhere. With public fields you can only control if the field is final or not. There are other reasons why you would use getters/setters, but this is probably the biggest one. Is it required to use getters/setters? No, but it is generally a good idea. Efficiency is generally not a concern.

    There's a big difference between "working code" and "good code". You asked us how good the code is, and we answered appropriately. This is the hallmark of good code reviews: you want the other reviewers to be as critical as possible and scrutinize in theory every line of code. This helps to catch any problems there could be, and generally the goal is to make your code better. I hope you don't consider any of our remarks as personal attacks, they aren't. Our goal is to help you write better code, so we pointed out areas that needed improvement. The last thing you want is for a reviewer to omit comments about poor code.

    If the code works for you, that's great. Honestly, I have written many pieces of "bad" code and continue to do so because I wanted/needed something "quick and dirty". They worked for what I needed, and I would not go back and put the effort in to fix the code to be "good" code because it's just not worth the effort. However, if I'm ever planning on using a piece of code for any extended period of time (more than an obscure "one-off" project), I will usually put significant effort into improving my code so when I or anyone else needs to use that code in the future it will work better and be easier to use. You'll need to weigh the same factor for your code, and you may make changes or not. Your choice.

  9. The Following 2 Users Say Thank You to helloworld922 For This Useful Post:

    BurningCa007 (March 14th, 2013), Norm (March 13th, 2013)

  10. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Quote Originally Posted by BurningCa007 View Post
    I mean the code works, why is it as if I've committed some sort of programming blasphemy with regards to this code?
    You asked us to criticize your code. If that wasn't what you were looking for, you shouldn't have asked us to do it.

    If the code works, great! But if you're asking us to rate it, this is pretty poorly written (or generated, as it were)- and that's okay, everybody writes messy code when they're first learning! But you asked us to critique the code, so that's what we're doing.

    The best advice I can give you is to ditch the gui builder, right now.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Are you going to try rewriting the code now that you have had these suggestions?
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Quote Originally Posted by Norm View Post
    Are you going to try rewriting the code now that you have had these suggestions?
    Uhm, I might do provided I have the time to stop focusing on school and homework for a while. This stuff usually won't let me sleep for days...

    Somehow, romanticizing with a couple inch thick book just isn't working out for me. I wish I took programming lessons with a real person, sadly that just ain't available to me.

    --- Update ---

    Latest code:

     
    package GUI;
     
    /**
     *
     * @author Redacted
     */
    public class CalculatorGUI extends javax.swing.JFrame {
     
        public double firstDouble; // the first value is stored here
        public double secondDouble; // the second value is stored here
        public double answer = 0; // self-explanatory, spiteful comment
        boolean operatorIsSelected = false; // used to know if a value is firstDouble or secondDouble
        String operators = ""; // used to denote operator to be used in calculation
     
        /**
         * Creates new form CalculatorGUI
         */
        public CalculatorGUI() {
            initComponents();
            result.setText(""); // ensures calculator screen is clear
     
        }
     
        /* The following code allows values to be set on the calculator screen and
         manipulated. */
        private void operation(String value){
            String text = result.getText();
            if (text.length() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + value);
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + value);
                }
            } else {
                result.setText(value);
            }
        }
     
        /**
         * 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")
    <!-- redacted to save space -->                     
     
        private void oneActionPerformed(java.awt.event.ActionEvent evt) {                                    
     
    operation("1");
        }                                   
     
        private void twoActionPerformed(java.awt.event.ActionEvent evt) {                                    
     
    operation("2");
        }                                   
     
        private void threeActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    operation("3");
        }                                     
     
        private void fourActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("4");
        }                                    
     
        private void fiveActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("5");
        }                                    
     
        private void sixActionPerformed(java.awt.event.ActionEvent evt) {                                    
     
    operation("6");
        }                                   
     
        private void sevenActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    operation("7");
        }                                     
     
        private void eightActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    operation("8");
        }                                     
     
        private void nineActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("9");
        }                                    
     
        private void zeroActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("0");
        }                                    
     
        private void clearAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            result.setText("");
            firstDouble = 0;
            secondDouble = 0;
        }                                        
     
        private void resultActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // This is the calculator screen, do not edit as all the other buttons manipulate this.
        }                                      
     
        private void divisionActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("/");
            operatorIsSelected = true;
            operators = "/";
        }                                        
     
        private void multiplicationActionPerformed(java.awt.event.ActionEvent evt) {                                               
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("X");
            operatorIsSelected = true;
            operators = "*";
        }                                              
     
        private void additionActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("+");
            operatorIsSelected = true;
            operators = "+";
        }                                        
     
        private void subtractionActionPerformed(java.awt.event.ActionEvent evt) {                                            
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("-");
            operatorIsSelected = true;
            operators = "-";
        }                                           
     
        private void equalsActionPerformed(java.awt.event.ActionEvent evt) {                                       
     
            secondDouble = Double.parseDouble(result.getText());
     
            switch (operators) {
                case "/":
                    answer = firstDouble / secondDouble;
                    operators = "";
                    break;
                case "*":
                    answer = firstDouble * secondDouble;
                    operators = "";
                    break;
                case "+":
                    answer = firstDouble + secondDouble;
                    operators = "";
                    break;
                case "-":
                    answer = firstDouble - secondDouble;
                    operators = "";
                    break;
            }
     
            result.setText("" + answer + "");
     
        }                                      
     
        /**
         * @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(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.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 CalculatorGUI().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton addition;
        private javax.swing.JButton clear;
        private javax.swing.JButton clearAll;
        private javax.swing.JButton decimal;
        private javax.swing.JButton division;
        private javax.swing.JButton eight;
        private javax.swing.JButton equals;
        private javax.swing.JButton five;
        private javax.swing.JButton four;
        private javax.swing.JButton multiplication;
        private javax.swing.JButton nine;
        private javax.swing.JButton one;
        private javax.swing.JFormattedTextField result;
        private javax.swing.JButton seven;
        private javax.swing.JButton six;
        private javax.swing.JButton subtraction;
        private javax.swing.JButton three;
        private javax.swing.JButton two;
        private javax.swing.JButton zero;
        // End of variables declaration                   
    }

    Please tell me if this is better.

  13. #12
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Here's my latest code

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package GUI;
     
    /**
     *
     * @author redacted
     */
    public class CalculatorGUI extends javax.swing.JFrame {
     
        public double firstDouble; // the first value is stored here
        public double secondDouble; // the second value is stored here
        public double answer = 0; // self-explanatory, spiteful comment
        boolean operatorIsSelected = false; // used to know if a value is firstDouble or secondDouble
        String operators = ""; // used to denote operator to be used in calculation
     
        /**
         * Creates new form CalculatorGUI
         */
        public CalculatorGUI() {
            initComponents();
            result.setText(""); // ensures calculator screen is clear
     
        }
     
        /* The following code allows values to be set on the calculator screen and
         manipulated. */
        private void operation(String value){
            String text = result.getText();
            if (text.length() > 0 && operatorIsSelected == false) {
                result.setText(result.getText() + value);
            } else if (operatorIsSelected == true) {
                for (int i = 0; i < 1;) {
                    result.setText(null);
                    i++;
                    operatorIsSelected = false;
                    result.setText(result.getText() + value);
                }
            } else {
                result.setText(value);
            }
        }
     
        /**
         * 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")
       <!-- redacted to save space -->                       
     
        private void oneActionPerformed(java.awt.event.ActionEvent evt) {                                    
     
    operation("1");
        }                                   
     
        private void twoActionPerformed(java.awt.event.ActionEvent evt) {                                    
     
    operation("2");
        }                                   
     
        private void threeActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    operation("3");
        }                                     
     
        private void fourActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("4");
        }                                    
     
        private void fiveActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("5");
        }                                    
     
        private void sixActionPerformed(java.awt.event.ActionEvent evt) {                                    
     
    operation("6");
        }                                   
     
        private void sevenActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    operation("7");
        }                                     
     
        private void eightActionPerformed(java.awt.event.ActionEvent evt) {                                      
     
    operation("8");
        }                                     
     
        private void nineActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("9");
        }                                    
     
        private void zeroActionPerformed(java.awt.event.ActionEvent evt) {                                     
     
    operation("0");
        }                                    
     
        private void clearAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            result.setText("");
            firstDouble = 0;
            secondDouble = 0;
        }                                        
     
        private void resultActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // This is the calculator screen, do not edit as all the other buttons manipulate this.
        }                                      
     
        private void divisionActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("/");
            operatorIsSelected = true;
            operators = "/";
        }                                        
     
        private void multiplicationActionPerformed(java.awt.event.ActionEvent evt) {                                               
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("X");
            operatorIsSelected = true;
            operators = "*";
        }                                              
     
        private void additionActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("+");
            operatorIsSelected = true;
            operators = "+";
        }                                        
     
        private void subtractionActionPerformed(java.awt.event.ActionEvent evt) {                                            
     
            String numberwords = result.getText();
            firstDouble = Double.parseDouble(numberwords);
            result.setText("-");
            operatorIsSelected = true;
            operators = "-";
        }                                           
     
        private void equalsActionPerformed(java.awt.event.ActionEvent evt) {                                       
     
            secondDouble = Double.parseDouble(result.getText());
     
            switch (operators) {
                case "/":
                    answer = firstDouble / secondDouble;
                    operators = "";
                    break;
                case "*":
                    answer = firstDouble * secondDouble;
                    operators = "";
                    break;
                case "+":
                    answer = firstDouble + secondDouble;
                    operators = "";
                    break;
                case "-":
                    answer = firstDouble - secondDouble;
                    operators = "";
                    break;
            }
     
            result.setText("" + answer + "");
     
        }                                      
     
        /**
         * @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(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.class
                        .getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(CalculatorGUI.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 CalculatorGUI().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton addition;
        private javax.swing.JButton clear;
        private javax.swing.JButton clearAll;
        private javax.swing.JButton decimal;
        private javax.swing.JButton division;
        private javax.swing.JButton eight;
        private javax.swing.JButton equals;
        private javax.swing.JButton five;
        private javax.swing.JButton four;
        private javax.swing.JButton multiplication;
        private javax.swing.JButton nine;
        private javax.swing.JButton one;
        private javax.swing.JFormattedTextField result;
        private javax.swing.JButton seven;
        private javax.swing.JButton six;
        private javax.swing.JButton subtraction;
        private javax.swing.JButton three;
        private javax.swing.JButton two;
        private javax.swing.JButton zero;
        // End of variables declaration                   
    }

    The most probable reason why my code is so terrible is cause I rarely have time to do it and when I do it detracts from everything else I have to do, and the questions I want to ask often result in no to strange answers. I guess that's what you get for romanticizing with a book...

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    There is still this strange "loop"
           for (int i = 0; i < 1;) {  //  Why a loop that will never loop
                    result.setText(null);   //  Why set null here when the value is set again below???
                    i++;                           //  why increment loop control value
                    operatorIsSelected = false;
                    result.setText(result.getText() + value);  //  why getText() when above set to null??
            }
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    BurningCa007 (March 14th, 2013)

  16. #14
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    removing the for and its curly brackets makes the code work perfectly, I honestly don't know why I put that there, perhaps I wasn't thinking straight. Anyhow, anything else?

  17. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Why are there 10 almost identical, one line methods?
    If you don't understand my answer, don't ignore it, ask a question.

  18. #16
    Junior Member BurningCa007's Avatar
    Join Date
    Mar 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Rate this code on a scale from 1 - 10 and please suggest some improvements.

    Quote Originally Posted by Norm View Post
    Why are there 10 almost identical, one line methods?
    As they all call another method to set numbers.

Similar Threads

  1. Dollar Rate
    By kanna39 in forum Java Theory & Questions
    Replies: 0
    Last Post: November 3rd, 2012, 05:50 AM
  2. Something I Whipped Up... Advice for Improvements?
    By snowguy13 in forum AWT / Java Swing
    Replies: 0
    Last Post: April 22nd, 2012, 03:55 PM
  3. [SOLVED] Scale Numbers from 0.0f to 1.0f
    By techwiz24 in forum Java Theory & Questions
    Replies: 1
    Last Post: September 23rd, 2011, 09:50 PM
  4. Optimize/Improvements/Suggestions for my code
    By JimmyNeutron in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 29th, 2011, 02:57 PM
  5. my code displaying some minor wrong o/p ....plz suggest me an answer !
    By naved in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 28th, 2011, 11:59 AM