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

Java中如何在另一类输出某类捕获的输入?附BMI计算代码问题

问题分析与修正方案

我来帮你梳理下代码里的问题,以及对应的解决办法:

核心问题1:局部变量遮蔽了类成员变量

你在patinfos方法里重新定义了name、age、height、weight这些变量(比如String name=sc.nextLine();),这些是方法内的局部变量,和类里声明的成员变量完全是两个独立的变量。方法执行完后,局部变量就会被销毁,类的成员变量还是保持默认值(String默认null,int默认0,double默认0.0),所以输出的时候就会显示null或空白。

核心问题2:静态方法访问非静态成员变量

你的patinfos是静态方法,但类里的name、age等都是非静态成员变量。静态方法属于类本身,不依赖实例存在,所以直接在静态方法里给非静态成员赋值是不符合Java逻辑的——它根本无法关联到具体实例的成员变量。


修正后的代码

package programspractice;
import java.util.Scanner;

class bmipatino {
    Scanner sc=new Scanner(System.in); // 改成非静态,和实例绑定
    String name;
    int age;
    double height;
    double weight;

    // 改成非静态方法,这样可以访问当前实例的成员变量
    void patinfos() {
        System.out.println("Enter the name of the Patient ");
        name = sc.nextLine(); // 直接给成员变量赋值,不再定义局部变量
        System.out.println("Enter the age of patient ");
        age = sc.nextInt();
        System.out.println("Enter the Height of patient");
        height = sc.nextDouble();
        System.out.println("Enter Weight of the patient");
        weight = sc.nextDouble();
    }
}

public class BmiUsingMethods extends bmipatino {
    void vitals() {
        System.out.println("Patients name is "+ name); // 不需要super,直接访问父类的成员变量
        System.out.println("Patients Age is "+ age);
        System.out.println("Patients Height is "+ height);
        System.out.println("Patients Weight is "+ weight);
    }

    public static void main(String[] args) {
        BmiUsingMethods ref = new BmiUsingMethods();
        ref.patinfos();
        ref.vitals();
    }
}

额外优化建议

如果之后需要在patinfos方法里同时使用同名的局部变量和成员变量,可以用this关键字明确指向成员变量,比如this.name = sc.nextLine();,这样代码可读性更高,也能彻底避免变量遮蔽的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:28:52