Results 1 to 15 of 15
- 02-27-2011, 07:02 PM #1
Member
- Join Date
- Jan 2011
- Posts
- 18
- Rep Power
- 0
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 } }
- 02-27-2011, 07:22 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-27-2011, 07:26 PM #3
Member
- Join Date
- Nov 2008
- Posts
- 11
- Rep Power
- 0
If i enter a non-numeric value the program raise an exception. Get in the habit of error checking.
- 02-27-2011, 07:30 PM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,545
- Rep Power
- 11
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):
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.Java Code:// where hours worked is not positive... // ... print error message // ... and get new value
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).
- 02-27-2011, 07:40 PM #5
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,545
- Rep Power
- 11
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.
- 02-28-2011, 01:36 AM #6
Member
- Join Date
- Jan 2011
- Posts
- 18
- Rep Power
- 0
Thanks to everyone for their suggestions.
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?
- 02-28-2011, 04:25 AM #7
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();
- 02-28-2011, 05:44 AM #8
Member
- Join Date
- Feb 2011
- Posts
- 3
- Rep Power
- 0
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){}
- 02-28-2011, 10:26 AM #9
Member
- Join Date
- Jan 2011
- Posts
- 18
- Rep Power
- 0
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.
- 02-28-2011, 10:35 AM #10
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-28-2011, 11:06 AM #11
Member
- Join Date
- Jan 2011
- Posts
- 18
- Rep Power
- 0
- 02-28-2011, 11:07 AM #12
Member
- Join Date
- Feb 2011
- Posts
- 3
- Rep Power
- 0
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.........)
- 02-28-2011, 11:19 AM #13
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-28-2011, 11:20 AM #14
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
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.
- 03-01-2011, 01:43 AM #15
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
-
latest jboss server
By uthpalaw in forum Enterprise JavaBeans (EJB)Replies: 2Last Post: 02-15-2011, 06:23 AM -
Play the latest
By jsntg in forum New To JavaReplies: 3Last Post: 10-08-2010, 04:43 AM -
Latest Jobs in Dubai
By julia in forum Jobs OfferedReplies: 1Last Post: 08-25-2009, 10:30 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks