Results 1 to 15 of 15
  1. #1
    phixion is offline Member
    Join Date
    Jan 2011
    Posts
    18
    Rep Power
    0

    Default Am I developing any bad habits: latest assignment inside

    Below is my lastest completed assignment and everything works as it should.

    I've been learning Java for about a month, and with the class size being fairly large, we don't spend much time reviewing previous assignments. On top of that, I don't want to waste class time asking the professor to review my code. My question: with this small bit of code, do you see any bad habits I am developing? If so, I wish to correct them now as opposed to later down the road.

    *I'm sure there are other ways to write this program. I am just using what I've learned thus far. If there is a bit of code that could be written easier/more efficiently, let me know as I would love to learn it.

    Thanks in advance.

    Java Code:
    import java.util.Scanner; //imports the Scanner class for use; user input
    
    public class proj3_4
    {
        public static void main (String[]args)  //main method
        {
            double hourlyWage, hoursWorked;               //declaring input variables
            double regularPay, overtimePay, totalPay;    //declaring output variables
    
            Scanner keyboard = new Scanner(System.in);  //creates a new instance of the Scanner class called keyboard
            
            while(true)
            {
                 System.out.print("Enter your hourly wage: ");  //print statment asking for hourly wage
                 hourlyWage = keyboard.nextDouble();           //sets the hourlyWage to the user input value
                 
                     while(hourlyWage <= 0) //while loop which checks if the hourlyWage entered is greater than 0
                     {
                         System.out.println("Error: The hourly wage must be greater than zero.");  //print error statement
                         System.out.println();                           //print a blank line
                         System.out.print("Enter your hourly wage: ");  //print statement asking again for the houly wage because the previously entered value was <= 0
                         
                         hourlyWage = keyboard.nextDouble();           //again setting the hourlyWage variable to the user's value
                     }
                 
                 System.out.print("Enter your total hours worked for the week: "); //print statement 
                 hoursWorked = keyboard.nextDouble();                             //sets the hoursWorked variable to the user input value
                    
                     while(hoursWorked <= 0)  //while loop which checks if the hoursWorked entered is greater than 0
                     {
                         System.out.println("Error: The total number of hours worked must be greater than zero."); //print error statement
                         System.out.println();                                 //prints a blank line
                         System.out.print("Enter your total hours worked: "); //print statement asking again for the hoursWorked because the previously entered value was <= 0
                         
                         hoursWorked = keyboard.nextDouble();                //again setting the hoursWorked variable to the user's value
                     }
    
                     if(hoursWorked > 40){  //if the user worked over 40 hours that week, calculate the overtime pay                  
                         overtimePay = (hoursWorked - 40) * (hourlyWage * 1.5);   //calculating the overtime pay
                     } else {                                                    //if the user didnt work over 40 hours, calculate the pay
                         overtimePay = 0;                                       //because the user didnt work any overtime (< 40), the overtime pay would be 0.
                     }
                    
                 regularPay = hourlyWage * hoursWorked;                                       //initializing, and the calculation for regularPay
                 totalPay = regularPay + overtimePay;                                        //initializing, and the calculation for totalPay
                
                 System.out.println();                                                     //prints a blank line
                 System.out.println("Total Regular Pay: $" + roundResult(regularPay));    //prints the regular pay, rounded to two decimal places
                 System.out.println("Total Overtime Pay: $" + roundResult(overtimePay)); //prints the overtime pay, rounded to two decimal places
                 System.out.println("Gross Weekly Pay: $" + roundResult(totalPay));     //printing the total pay, rounded to two decimal places
                 System.out.println();                                                 //prints a blank line
            } 
        }
        
        public static double roundResult(double num)  //rounding method with parameter num
        {
            num = num * 100;                       //moving the decimal two places to the right
            num = Math.round(num);                //rounding the value of num
            num = num / 100;                     //moving the decimal to places to the left
            
            return num;                        //returning the rounded result
        }
    }

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default

    Sticking all your program logic in one big (main) method is an extremely bad habit. An old unix/C rule is: let your functions/methods do one thing and let them do it well. Don't be afraid to write small one-line methods. It pays back.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    ziggy is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    If i enter a non-numeric value the program raise an exception. Get in the habit of error checking.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Comments on comments...

    There are a huge number of them! This isn't, in itself, a bad habit because while you are learning comments can be very useful at keeping things straight. But you should only comment what *you* think needs commenting.

    "System.out.println(); //prints a blank line" is a case in point. Maybe once, but the constant repetition...? The point is that comments that are *useful* can become lost in the noise of comments that aren't.

    When I was first writing code I used to comment very heavily - and my style was to right align the comments, which I recognised weren't a feature of "real" code, so the code could visually stand on its own.

    I also adopted a very consistent grammatical style: you switch between "printing the total..." and "prints a ...". Not that I'm claiming it as a "rule", but I used the imperative as if I were talking to the computer, "print the total...", "print a" etc. Also I used elipses where blocks of code were involved (and stopped right aligning):

    Java Code:
    // where hours worked is not positive...
    // ... print error message
    
    // ... and get new value
    Such comments which describe the detail of what is going on should not replace documentation of the methods etc using standard javadoc conventions. They are very different things: the javadoc comments are addressed "outwards" to a hypothetical programer using your code rather than "inwards" at the mechanics of the code. The programer is more interested in what the code does rather thanhow it does it.

    The Javadoc comments are the ones you will rely on later. If you google about there are guides/standards for javadoc comments (again, they aren't laws).

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Rounding numerical values is often the wrong thing to do. ("Rounding" here means changing the numeric value so that it is approximately - to within the computer's precision - equal to multiple of some power of 10. It can only become less accurate as a result.)

    More often what you want to do is change a numeral - a string representing a numeric quantity. ("Rounding" here means leaving the numeric quantity alone but altering the string so that it looks nice.) This is usually referred to as formatting.

    There is a DecimalFormat class that helps with formatting. And a format() method in String and printf() method in various classes.

  6. #6
    phixion is offline Member
    Join Date
    Jan 2011
    Posts
    18
    Rep Power
    0

    Default

    Thanks to everyone for their suggestions.

    Quote Originally Posted by ziggy View Post
    If i enter a non-numeric value the program raise an exception. Get in the habit of error checking.
    Since you posted this, I have been trying to put some error checking into the program with no luck. My goal is to not allow the user to input a zero, and also for the program to check if a non-numeric value was entered.

    Is there a way of doing those two things without importing another library to use? If so, could you point me in the right direction?

  7. #7
    Zman3359's Avatar
    Zman3359 is offline Member
    Join Date
    Jan 2011
    Posts
    42
    Rep Power
    0

    Default

    Here is an example of checking to see if the input is a non-numeric value.
    Java Code:
    System.out.print("Enter your age: ");
    try
    {
       input = in.nextInt(); // Get the input
       in.nextLine(); // Get rid of the ENTER key left behind when the user hits enter ...
    		  // ... because nextInt(); ignores the ENTER key while nextLine() doesn't
    
       System.out.println("\nYour age is: " + input);
    }
    catch(InputMismatchException ime)
    {
       input = -999; // Give input a value if the input is incorrect
       System.out.println("ERROR: Please enter a whole number between 0 and 10");
    }

    It may not be good programming but this code snippet below will send the program flow into the catch block if the input value is less than 0 or greater than 10. Then you can just print whatever you want to say. You could also just check the value of the input in the try block and print something there, this might be better programming but I don't know.
    Java Code:
    if(input < 0 || input > 10)
    	    throw new InputMismatchException();

  8. #8
    Ravik is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    As a beginner, the code seems to be ok, but you should learn some Object oriented principles of code reusability.
    1.That much commenting is not required. Commenting should be functionality specific & precise.
    2.Use constructors for initialization.
    3.Break your code into two or more classes.
    4.Only specific methods must be called in main() method. Not whole code be put into it.
    5.Use exception handling
    6.No terminationg condition for loop, or use do-while
    7.Eg. code can be break into specific methods:
    calculateRegularPay(double hourlyWage,double hoursWorked){}
    calculateTotalPay(double regularPay,double overtimePay){}

  9. #9
    phixion is offline Member
    Join Date
    Jan 2011
    Posts
    18
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Sticking all your program logic in one big (main) method is an extremely bad habit. An old unix/C rule is: let your functions/methods do one thing and let them do it well. Don't be afraid to write small one-line methods.

    Quote Originally Posted by Ravik View Post
    7.Eg. code can be break into specific methods:

    calculateRegularPay(double hourlyWage,double hoursWorked){}
    calculateTotalPay(double regularPay,double overtimePay){}

    Why? Does it make the code more efficient? Is it strictly for readability purposes? I'm just trying to understand the reasoning behind those suggestions.

    I've searched on Google, but didn't find much help regarding those suggestions.

    *I'm not questioning in a negative way, I'm just trying to learn.

  10. #10
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by phixion View Post
    Why? Does it make the code more efficient? Is it strictly for readability purposes? I'm just trying to understand the reasoning behind those suggestions.

    I've searched on Google, but didn't find much help regarding those suggestions.

    *I'm not questioning in a negative way, I'm just trying to learn.
    Think of an ordinary novel; if the story is presented without empty lines (paragraphs), separate chapters or anything it shows as one big blob of characters. If doesn't read comfortable. The same with those separate methods: it allows the reader to optionally skip a certain part of detail. If everything is crammed in one huge method the reader has to wade through it.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    phixion is offline Member
    Join Date
    Jan 2011
    Posts
    18
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Think of an ordinary novel; if the story is presented without empty lines (paragraphs), separate chapters or anything it shows as one big blob of characters. If doesn't read comfortable. The same with those separate methods: it allows the reader to optionally skip a certain part of detail. If everything is crammed in one huge method the reader has to wade through it.

    Understood, thanks. Could separating code into multiple methods cause any slow down in a program's execution? In other words, could reading or calling multiple methods cause a decrease in "performance"? Ha, I hope that makes sense.

  12. #12
    Ravik is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    At this small piece of code, you can follow any way of doing it whichever you like, but talking of best code practices, you have to code in such a way so that it can be reusable. The most important aspect of any object oriented programming is code reusability. Here are more advantages
    1.In this way, the same code and be used anywhere without having to rewrite it.
    2.Improves code readability(by third person)
    3.Changes are easy to make.
    4.Easy to find and fix bugs.
    (Think of coding 10000 lines using same approach as you did in your code.........)

  13. #13
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by phixion View Post
    Understood, thanks. Could separating code into multiple methods cause any slow down in a program's execution? In other words, could reading or calling multiple methods cause a decrease in "performance"? Ha, I hope that makes sense.
    A method call takes a teenzy weenzy little bit of time but it can improve the structure of your code and make it overall more efficient. I've seen so much crap where the writer of that crapoloa had to bend over backwards by introducing temporary variables, boolean flag variables just to keep his/her code in control; the code almost disappeared on the right side of the screen, wobbling left and right continuously and going on and on and on forever.

    As a nice test for yourself you should be able to describe what a method does with just enough detail in just one sentence. If you stitch those sentences together it should read like an understandable story. The sentence for your main( ... ) method should just be "fire up the entire application". Your private methods handle one small detail of the problem; i.o.w. the word "and" is not allowed in a sentence that describes the functionality of a single method.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,746
    Rep Power
    19

    Default

    Quote Originally Posted by phixion View Post
    Understood, thanks. Could separating code into multiple methods cause any slow down in a program's execution? In other words, could reading or calling multiple methods cause a decrease in "performance"? Ha, I hope that makes sense.
    9 times out of ten (at least) maintainability is more important than any preconceived notions of what will make your code perform better. Performance is normally architectural in nature (with some exceptions), and bottlenecks are also notoriously difficult to spot before you've done any performance tests.

    Well-written code, that is code written with an eye to maintainability, will (funnily enough) also be code that is relatively easy to alter should a bottleneck be identified.

  15. #15
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    6

    Default

    I agree with Tolls - while technically a method call vs direct access is slightly slow, we're talking nano-seconds. You have any idea how small of a time increment that is? Its easy to test. Write an app that calls a method millions of times vs one that access a variable directly millions of times. Make sure to average the test cases, so lets say do a million cycles. You might find a couple millisecond difference between the two. However, the loss of good OOP code is a much greater loss than a couple of CPU cycles.

Similar Threads

  1. latest jboss server
    By uthpalaw in forum Enterprise JavaBeans (EJB)
    Replies: 2
    Last Post: 02-15-2011, 06:23 AM
  2. Play the latest
    By jsntg in forum New To Java
    Replies: 3
    Last Post: 10-08-2010, 04:43 AM
  3. Latest Jobs in Dubai
    By julia in forum Jobs Offered
    Replies: 1
    Last Post: 08-25-2009, 10:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •