Using local declared variables in a different meth

2020-04-19 05:13发布

问题:

I am having a little difficulty with a school assignment, long story short I declared two local variables in a method and I need to access those variables outside the method :

 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;
}

I would have to print the following string in a different method :

    System.out.println("Height: " + resultFeet + " feet " + resultInches + " inches");

Any suggestions?

Thank you.

回答1:

You can't access local variables outside of the scope they are defined. You need to change what is return by the method

Start by defining a container class to hold the results...

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;
    }

}

Then modify the method to create and return it...

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);
}


回答2:

You can't access local variables from method A in method B. That's why they are local. Take a look: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

I recommend to use solution written by @MadProgrammer - create class which contains feet and inches.



回答3:

You need to create a shared variable that holds your result or you encapsulate the result in a single object and then return to caller method, it may be class like result

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

  public Result(int resultFeet, int resultInches) {
    this.resultFeet = resultFeet;
    this.resultInches = resultInches;
  }
}

Now, you make a result,

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);
}

Use this result in other function to print result.

    Result result = convertHeightToFeetInches(<your_input>);
    System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")