Tim Driven Development | Test until the fear goes away
Tim Cooke wrote:Neither of them compile for me because "result" is not defined.
There is no need to have any state in the factorial function, which means you don't need the "result" variable at all. Have a think and see if you can simplify your function to not need any variables.
Campbell Ritchie wrote:
I don't think you should use *=. I don't think it will work.
Campbell Ritchie wrote:You know you can shorten those methods greatly? You can use the ?: operator to reduce them to one line.
I would use zero as a base case rather than 1, because 0 has a factorial which is 1.
I would also suggest that they are functions and in the most dubious classification of methods ever seen they all come out as 1368 (except the main method), so they should be considered candidates to be marked static.
I don't think you should use *=. I don't think it will work.
Don't make result a field. If you are using recursion you are straying into the realms of functional programming and a function should not alter fields or have any other such side‑effects.
If you are going to use recursion call the same method, so in fectorial3 call factorial3 not factorial. Also you can get rid of the local variables in the main method:-
System.out.println("z = " + obj.factorial3(5));
Is there actually a difference between the factorial method and factorial2?
You are displaying the correct answer from all three calls, but if you wrote ..."z = " + z... instead of + x things might become interesting
Not when I tried it, it wasn'tDave Tolls wrote: . . .
So result is always 1, for each and every call.
Just as well to make that sort of mistake where it doesn't matter.Ranajoy Saha wrote: . . . I wrote the print statement for the x variable and then copied the entire things . . .
Campbell Ritchie wrote:
Not when I tried it, it wasn'tDave Tolls wrote: . . .
So result is always 1, for each and every call.
Dave Tolls wrote: . . .
And (for laughs) here's some additional logging:
. . .