为了理解类/继承,我正在编写java程序来计算bmi,我的程序中有2个类,一个是输入,另一个类是显示输出。但是,我无法从输出窗口看到我捕获的输入,而是看到null / blanks
请找到该程序,并帮助我/指导正确的代码。
Package programspractice;
import java.util.Scanner;
class bmipatino
{
static Scanner sc=new Scanner(System.in);
String name;
int age;
double height;
double weight;
static void patinfos()
{
System.out.println("Enter the name of the Patient ");
String name=sc.nextLine();
System.out.println("Enter the age of patient ");
int age=sc.nextInt();
System.out.println("Enter the Height of patient");
double height=sc.nextDouble();
System.out.println("Enter Weight of the patient");
double weight =sc.nextDouble();
}
}
public class BmiUsingMethods extends bmipatino
{
void vitals()
{
System.out.println("Patients name is "+super.name);
System.out.println("Patients Age is "+super.age);
System.out.println("Patients Height is "+super.height);
System.out.println("Patients Weight is "+super.weight);
}
public static void main(String[] args)
{
BmiUsingMethods ref = new BmiUsingMethods();
ref.patinfos();
ref.vitals();
}
}
答案 0 :(得分:0)
您的代码中存在多个问题。您的patinfos()
是静态的,因此值不会绑定到类的特定实例。
您在此静态方法中重新定义名称,年龄等,并且它们会影响实例变量。
因此,如果删除static关键字和局部变量声明,这将起作用:
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();
}