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

Java技术问询:能否通过构造方法传递方法所需变量?

当然可以通过构造方法传递所需变量!

没问题呀,完全可以通过构造方法来传递对象初始化(或者后续方法用到的)变量,这其实是Java里初始化对象成员变量的标准操作之一~

先看你写的代码:

你的Recording类已经正确实现了通过构造方法传递变量的逻辑:

public class Recording {
    public int height;
    public int diameter;
    public int weight;
    public Recording (int height, int diameter, int weight) {
        this.height = height;
        this.diameter = diameter;
        this.weight = weight;
    }
}

这个构造方法接收三个int类型的参数,然后把它们赋值给类的成员变量,这样在创建Recording对象时,就能直接把需要的变量传递进去,完成对象的初始化,非常标准!

给你提两个代码里的小问题:

  • System.in.read()的使用误区:你在Leergut类里想用System.in.read()来获取输入传递给构造方法,但要注意System.in.read()读取的是单个字符的ASCII值,比如你输入数字10,它只会返回字符'1'的ASCII码49,而不是整数10。如果要读取整数输入,建议用Scanner类来处理。
  • 局部变量未初始化:Leergut里的code变量在while循环前没有赋值,直接写while (code != -1)会编译报错,因为Java要求局部变量必须先初始化才能使用。

调整后的Leergut类示例:

import java.util.Scanner;

public class Leergut {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int height;
        int diameter;
        int weight;
        int code = 0; // 先初始化code
        int pfand;
        
        while (code != -1) {
            // 读取用户输入的三个参数
            System.out.print("请输入高度:");
            height = scanner.nextInt();
            System.out.print("请输入直径:");
            diameter = scanner.nextInt();
            System.out.print("请输入重量:");
            weight = scanner.nextInt();
            
            // 通过构造方法传递变量创建Recording对象
            Recording r = new Recording(height, diameter, weight);
            
            // 这里可以添加处理r对象的逻辑,比如打印属性值
            System.out.println("创建的Recording对象:height=" + r.height + ", diameter=" + r.diameter + ", weight=" + r.weight);
            
            // 输入code判断是否退出循环
            System.out.print("请输入编码(输入-1退出):");
            code = scanner.nextInt();
        }
        scanner.close(); // 关闭Scanner资源
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:01:31