Using local declared variables in a different method in Java

后端 未结 3 1453
后悔当初
后悔当初 2021-01-25 18:49

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 : <

3条回答
  •  粉色の甜心
    2021-01-25 19:19

    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();
        System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")
    

提交回复
热议问题