📅  最后修改于: 2023-12-03 15:40:06.040000             🧑  作者: Mango
在Java语言中,方法是编写程序的基本单元之一。编写规范、易读易懂的方法是良好编程习惯的一部分。下面是一些方法的Java编码标准。
例如,在计算数字平方的情况下,建议使用calculateSquare
。
例如,在计算平均值的情况下,建议使用calculateAverage(double[] numbers)
而不是calculateAverage(double[] allNumbers, int length)
。
void
作为返回类型例如,
/**
* Calculates the average of the given numbers.
*
* @param numbers the numbers to calculate the average of
* @return the calculated average
* @throws IllegalArgumentException if numbers is null or empty
*/
public static double calculateAverage(double[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Input array must contain at least one number");
}
double sum = 0;
for (double number : numbers) {
sum += number;
}
return sum / numbers.length;
}
/**
* This method will calculate the total cost of items.
*
* @param items list of items
* @param quantity quantity of items
* @param price price per item
* @return total cost of items
*/
public double calculateTotalCost(List<Item> items, List<Integer> quantity, double price) {
if (items == null || quantity == null || items.isEmpty() || quantity.isEmpty() || items.size() != quantity.size()) {
throw new IllegalArgumentException("Invalid input!");
}
double total = 0.0;
for (int i = 0; i < items.size(); i++) {
Item item = items.get(i);
int count = quantity.get(i);
total += item.getPrice() * item.getDiscount() * count;
}
return total;
}