You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java自定义calculationsMethod方法无法在main中调用如何解决

问题解决方法

核心问题

原来的calculationsMethod没有定义入参,无法接收main方法中读取到的长和宽,且方法内部引用的length、breadth是main方法的局部变量,方法外部无法直接访问,所以直接调用会报错。

修改步骤

  • 第一步:修改calculationsMethod的方法签名,添加两个Float类型的形参,用来接收传入的长和宽
  • 第二步:在main方法中调用calculationsMethod时,把读取到的length和breadth作为实参传入
  • 可选优化:原方法中计算了面积但没有输出,可补充面积的打印语句

修改后完整代码

import java.util.Scanner;
public class JavaHomework1 {

    // 新增形参接收长和宽
    static void calculationsMethod(Float length, Float breadth) {
        Float perimeter = 2 * length + 2 * breadth;
        Float area = length * breadth;
        System.out.println("The Perimeter of the Rectangle is " + perimeter);
        // 补充打印面积(不需要可以删除该行)
        System.out.println("The Area of the Rectangle is " + area);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input the length of the rectangle: ");
        Float length = input.nextFloat();

        System.out.println("Input the breadth of the rectangle: ");
        Float breadth = input.nextFloat(); 
        input.close();
        // 调用方法时传入读取到的长和宽
        calculationsMethod(length, breadth);
    }
}

运行说明

运行程序后按提示输入矩形的长和宽,就会自动调用方法完成计算,并输出对应的周长和面积结果。

内容的提问来源于stack exchange,提问作者Ani2906

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:54:03