My first Java program.

The improvements everyone has suggested thus far are good, and I'd echo celegorm's point about not expecting user input to be sanitised - some very famous and expensive programming mistakes have happened this way, and no doubt many more will happen in the future. I'm not sure I'd go as far as to do the same thing for, say, UI controls that can only accept numbers - I haven't known a version of Java that broke something that fundamental, and I'd argue that the excess code here harms readability more than the benefit you'd gain in such a corner case. But I agree with the principle, and functionally at least it can't do any harm to double check.

Where I will chime in is on style - overall it's not bad, but just a few points that I think are worth mentioning:
  • Inline Comments - You've got a lot of comments in your code like "//print message" and so on. Look at any piece of code written by a beginner and they'll almost always put these in, look at any piece of code written by a professional, and apart from in odd corner cases, you won't find any. That's because too many comments in the wrong places can actually *hurt* readability of the code. If you feel that you must comment something this way, then you should really break it up into separate methods and use:
  • Javadoc comments. These are what professionals *do* use, and I rarely see beginners use these - but they're what are often required in a professional setting. The javadoc tool takes these and generates the code documentation for you, so they're what people actually look at. Pretty much every method you write should be commented this way, in this format - they start "/**" and end "*/". See here for details - worth taking this on board
  • Indentation - it's pretty good, but there's a couple of cases (such as in your last return statement) where it doesn't quite line up. Get this right early on, otherwise when you're staring at complex code later it's really going to haunt you if you can't read through its flow simply.
  • Java is an OO language by nature, and while many people start just using static methods as defined here try not to go too far down this road before you start looking at objects. When you understand them then most coding should be done via objects, not static methods - all the main method should really do is instantiate an object or two and perhaps call a method or two on them. The rest should be handled in non-static code. (Just something to bear in mind for the future.)
 
Thanks for all your feedback guys! I am going to reasearch some more, I will keep everything you have said in mind in my next project. Thanks again
 
Back
Top Bottom