Bear Bibeault wrote:My advice would be to step away from the code for a minute and write, in English, the list of steps to take to accomplish this. Then, and only then, write code to implement it.
When you are codinig, you should spend 90% of your time THINKING, and only 10% TYPING. Never write a single line of code until you have a good idea in your head how you are going to solve the problem.
I generally start by writing out the steps I take in English, which is my native language. Then I refine them, breaking them down into smaller and smaller pieces, making my description more and more detailed. for this problem, it'd be something like this:
1) get a number
2) if the number is not a single digit
3) add up all the digits in the number to get a new number
4) return to step 2
5) if it is a single digit, we're done.
Ok, so i look at that. line 1 looks like it should be a method all to itself. Based on the code sample you provided, i'd assume that's already done.
Now, lined 2-4 look like they should be a loop of some kind. Line 3 all by itself looks like it should be a method.
now I can see writing a method that has a loop to see if I have a single digit, and return that if so. If not, I need to call another method that sums the digits.
So now I can break line 3 into individual steps. It's a method all to itself, so it doesn't care about how many times I've tried, how long the result is, or anything. All it has to do is sum the digits in whatever number it is given. Now I can code the method with the loop, or code this method. Whichever way I go, I can write some temporary code as a harness to test the piece I'm working on. Once I'm sure that piece works, I can then use it as I build the other pieces.
The idea is to separate out responsibility of tasks, so each method does one simple thing, does it well, and can be easily understood.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Get out of my mind! Look! A tiny ad!
Create Edit Print & Convert PDF Using Free API with Java