Java Reference
In-Depth Information
2. Every method should perform exactly one task. If a method becomes too big, try
breaking it down into several methods.
3. Avoid methods that contain a switch parameter. That is, a method that can perform
one of several tasks based on the value of an input parameter. Instead, create a separate
method for every task.
4. Any modification to the value of the input parameters of a method that are primitive
types (e.g., int , double , etc.) will not be seen by the calling the method. The reason is
that the input parameters are local variables for the method. Java uses pass-by-value
for primitive-type parameters.
5. Use global variables sparingly. Only define them when you need them. As a general
rule, define every variable in the innermost scope that you can live with.
6. Good programming practices call for every method to have an appropriate JavaDoc.
7. Use printf to produce formatted output. Remember that ā€œ%dā€ stands for decimal
(a.k.a., integer) and not double. Use ā€œ%fā€ to display a double .
8. Use the DecimalFormat class to specify a pattern for formatting a real number. For
example, the class can be used to display currency values.
9. Magic numbers are any numerical literals, such as 42, that appear in your program.
Avoid using magic numbers and define such numerical literals as constants at the
beginning of the class. For example, public static int MEANING OF LIFE = 42 .
10. Names of constants should be in all capital letters.
4.10 Exercises
1. Write a method that takes in three integers and returns the biggest.
2. Write a method that takes in three integers and returns the average as a double .
3. Write a method that takes as input a double and prints it to the screen formatted to
two digits after the decimal dot.
4. Write a method that takes as input an integer n and returns the sum of the first n num-
bers. For example, if the input is 10, the method will return 55 because 1+2+ ... +10
= 55.
5. Consider sales tax of 7%. Write a method that takes as input the price of an item
and returns the sales tax for that item. Both input and return value should be of type
double .
6. Write a method that computes the amount of a tip. The method should take as input
the total price for the meal. The method should return the amount for the tip. The
tip should be between 10% and 20%, where the program should use a random number
to determine the exact amount.
 
Search WWH ::




Custom Search