在Java中的不同方法中使用局部声明变量

在Java中的不同方法中使用局部声明变量,java,methods,local-variables,Java,Methods,Local Variables,我在学校作业中遇到了一些困难,长话短说,我在一个方法中声明了两个局部变量,我需要访问这些方法之外的变量: public String convertHeightToFeetInches(String input){ int height = Integer.parseInt(input); int resultFeet = height / IN_PER_FOOT; int resultInches = height % IN_PER_FOOT; Math.

我在学校作业中遇到了一些困难,长话短说,我在一个方法中声明了两个局部变量,我需要访问这些方法之外的变量:

 public String convertHeightToFeetInches(String input){

    int height = Integer.parseInt(input); 
    int resultFeet = height / IN_PER_FOOT;
    int resultInches = height % IN_PER_FOOT;
    Math.floor(resultInches);
    return input;
}
    System.out.println("Height: " + resultFeet + " feet " + resultInches + " inches");
我必须用不同的方法打印以下字符串:

 public String convertHeightToFeetInches(String input){

    int height = Integer.parseInt(input); 
    int resultFeet = height / IN_PER_FOOT;
    int resultInches = height % IN_PER_FOOT;
    Math.floor(resultInches);
    return input;
}
    System.out.println("Height: " + resultFeet + " feet " + resultInches + " inches");
有什么建议吗


谢谢。

您无法从方法B中的方法A访问局部变量。这就是为什么它们是局部变量。 看一看:

因此,局部变量只对使用它们的方法可见 被宣布;他们不能从班上的其他人那里得到


我建议使用@MadProgrammer-create类编写的解决方案,该类包含
feet
inches

您不能访问定义范围之外的局部变量。您需要更改该方法返回的内容

首先定义一个容器类来保存结果

public class FeetInch {

    private int feet;
    private int inches;

    public FeetInch(int feet, int inches) {
        this.feet = feet;
        this.inches = inches;
    }

    public int getFeet() {
        return feet;
    }

    public int getInches() {
        return inches;
    }

}
然后修改方法以创建并返回它

public FeetInch convertHeightToFeetInches(String input) {
    int height = Integer.parseInt(input);
    int resultFeet = height / IN_PER_FOOT;
    int resultInches = height % IN_PER_FOOT;
    Math.floor(resultInches);
    return new FeetInch(resultFeet, resultInches);
}

您需要创建一个保存结果的共享变量,或者将结果封装在单个对象中,然后返回调用方方法,它可能类似于类
result

public class Result {
  public final int resultFeet;
  public final int resultInches;

  public Result(int resultFeet, int resultInches) {
    this.resultFeet = resultFeet;
    this.resultInches = resultInches;
  }
}
现在,你得出一个结果

public Result convertHeightToFeetInches(String input){

    int height = Integer.parseInt(input); 
    int resultFeet = height / IN_PER_FOOT;
    int resultInches = height % IN_PER_FOOT;
    Math.floor(resultInches);
    return new Result(resultFeet, resultInches);
}
在其他函数中使用此结果打印结果

    Result result = convertHeightToFeetInches(<your_input>);
    System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")
Result-Result=convertHeightToFeetInches();
System.out.println(“高度:+result.resultFeet+“英尺”+result.resultInches+“英寸”)

您可以创建一个名为
FeetInches
的类,并从该方法返回
FeetInches
。为什么您的方法会返回输入?它应该返回转换,否?返回一个包含
英尺
英寸
属性的
实例