Using local declared variables in a different method in Java

后端 未结 3 1409
后悔当初
后悔当初 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:05

    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);
    }
    
    0 讨论(0)
  • 2021-01-25 19:09

    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.

    0 讨论(0)
  • 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(<your_input>);
        System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")
    
    0 讨论(0)
提交回复
热议问题