A method is a named block with typed parameters and a return type: static int rectangleArea(int width, int height) { return width * height; }. return hands the result back and ends the method; a method declared void returns nothing. Calling rectangleArea(3, 4) runs the body with those values. The static keyword means the method belongs to the class rather than to an object, which is all you need until the objects module.
Returning is different from printing. System.out.println shows a value to a person; return gives it to the code that called the method, which can store it, compare it, or pass it on. The checks call your methods and look at what comes back, so return, do not print.
Methods can live in any class. The library project needs a late fee calculation, so this lesson also adds a class Fees with one static method, which the project will call as Fees.lateFee(...).
static double circleArea(double radius) {
return Math.PI * radius * radius;
}
// in main:
double big = circleArea(10);
System.out.println(big > 300);Your task
In Main, write static int rectangleArea(int width, int height) returning the area, and static boolean isEven(int n) returning whether n is even.
Then, in the class Fees, write static int lateFee(int daysLate, int centsPerDay): 0 when daysLate is zero or less, otherwise daysLate * centsPerDay, but never more than 1000 cents.
Part of the final project. Fees works out the late fee for a returned book, capped at ten dollars. It is saved in this browser and loaded into Project: the library when you get there.
Hint 1
return width * height; and return n % 2 == 0; (the comparison is already a boolean).
Hint 2
if (daysLate <= 0) return 0; then return Math.min(daysLate * centsPerDay, 1000);
Show the solution
public class Main {
static int rectangleArea(int width, int height) {
return width * height;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
System.out.println(rectangleArea(3, 4));
}
}
class Fees {
static int lateFee(int daysLate, int centsPerDay) {
if (daysLate <= 0) {
return 0;
}
return Math.min(daysLate * centsPerDay, 1000);
}
}