Chapter 5 Methods
1. At least three benefits: (1) Reuse code; (2) Reduce complexity; (3) Easy to maintain.
See the Sections 4.2 and 4.3 on how to declare and invoke methods.
2. void
3. Yes. return (num1 > num2) ? num1 : num2;
4. True: a call to a method with a void return type is always a statement itself.
False: a call to a method with a nonvoid return type is always a component of an
expression.
5. A syntax error occurs if a return statement does not appear in a non-void method.
You can have a return statement in a void method, which simply exits the method.
But a return statement cannot return a value such as return x + y in a void method.
6. See Section 5.2.
7. Computing a sales commission given the sales amount and the commission rate
public static double getCommission(double salesAmount, double
commissionRate)
Printing a calendar for a month
public static void printCalendar(int month, int year)
Computing a square root
public static double sqrt(double value)
Testing whether a number is even and return true if it is
public static boolean isEven(int value)
Printing a message for a specified number of times
public static void printMessage(String message, int times)
Computing the monthly payment, given the loan amount,
number of years, and annual interest rate.
public static double monthlyPayment(double loan, int
numberOfYears, double annualInterestRate)
Finding the corresponding uppercase letter given a lowercase letter.
public static char getUpperCase(char letter)
8. Line 2: method1 is not defined correctly. It does not have a return type or void.
Line 2: type int should be declared for parameter m.
评论0
最新资源