Java方法与参数使用:如何正确调用void类型printRectangleDetails方法
解决方案
核心问题说明
- 你当前运行代码没有输出
printRectangleDetails的内容,是因为main方法中从未调用过该方法,方法内的逻辑自然不会执行 - 你当前定义的
printRectangleDetails参数不符合要求:任务明确要求仅需传入长、宽两个参数,面积、周长需要在方法内部调用已有的area、perimeter方法计算,不需要作为入参传入 - 你询问的「是否需要修改main方法」的答案是肯定的,任务要求替换main内原有代码为该方法的调用,直接修改即可
代码修改步骤
1. 重写printRectangleDetails方法并补充注释
调整参数为仅长、宽两个,内部自行计算面积、周长,补充标准JavaDoc注释:
/** * 打印矩形的详细信息,包括长、宽、面积、周长 * @param length 矩形的长 * @param width 矩形的宽 */ public static void printRectangleDetails(int length, int width) { // 内部调用现有方法计算面积和周长 int area = area(length, width); int perimeter = perimeter(length, width); System.out.println("The length of the rectangle is " + length); System.out.println("The width of the rectangle is " + width); System.out.println("The area of the rectangle is " + area); System.out.println("The perimeter of the rectangle is " + perimeter); }
void类型方法没有返回值,直接作为独立语句调用即可,不需要用变量接收返回结果
2. 替换main方法中的原有代码
删除原有两行打印语句,改为调用printRectangleDetails方法,传入长、宽参数即可:
public static void main(String[] args) { // 传入长10,宽15,直接调用方法即可触发打印 printRectangleDetails(10, 15); }
完整修改后代码
public class Rectangle { public static void main(String[] args) { printRectangleDetails(10, 15); } /** * Returns the area of a rectangle * @param length 矩形的长 * @param width 矩形的宽 * @return 矩形面积 */ public static int area (int length, int width) { return length * width; } /** * Returns the perimeter of the rectangle * @param length 矩形的长 * @param width 矩形的宽 * @return 矩形周长 */ public static int perimeter (int length, int width) { return 2 * (length + width); } /** * 打印矩形的详细信息,包括长、宽、面积、周长 * @param length 矩形的长 * @param width 矩形的宽 */ public static void printRectangleDetails(int length, int width) { int area = area(length, width); int perimeter = perimeter(length, width); System.out.println("The length of the rectangle is " + length); System.out.println("The width of the rectangle is " + width); System.out.println("The area of the rectangle is " + area); System.out.println("The perimeter of the rectangle is " + perimeter); } }
运行后会直接输出四行对应的矩形信息,符合要求。
内容的提问来源于stack exchange,提问作者emily
相关产品推荐
相关产品推荐

