you can directly return bill without the use of an additional double value. Also in the first case you can directly return bill *0.5. Lastly you can use the ternary operator ?: so your function is reduced to a single line of code.
Brian Pianczk wrote:
Is there a specific way to have the method be called with the return already formatted?
Again, a double is just a conceptual number; it does not include any kind of formatting. You can write the number 1/3 as 0.33333333333 or 0.3333 or 3.33x10-1, or many other different ways, but they're all represented by the same double value. Formatting happens only when you print a value.
If you want your method to return a specific formatted display of a number, and you'll never actually do any math on the returned value again, then you could have the method return a String, and put the format call into the method -- i.e.,
... but I wouldn't recommend this. Your original getBillAmount() did one thing: it computed a value. Your new one does two things: computes a value and formats it. In general, you want most of your methods to do just one thing -- that makes the code easier to read, and it's more flexible. If you had a lot of calculation methods and they all formatted their output, and now you decide you need to use a different format, you have to make changes all over the code! If, on the other hand, you did all your formatting and output in one place -- i.e., here, in main() -- then it'd be easy to make the change. So I actually think your original was just fine -- returning the double is a better plan.
Finally, about the advice you got to use the ternary operator: your original method was longer, yes, but it was also nicely self-documenting. The variables "discounted" and "notDiscounted" make the purpose of the code easy to understand. That "ternary operator" has its place, but it's something that should be used sparingly. Here, you've used it to turn a nice, clear, readable method into a terse, unreadable Perl-like blurt. Avoid clever, terse code -- and take all the style advice you get with a grain of salt. Always keep in mind that you, and others, might have to read the code again in a year. Which version would you rather find?