Using local declared variables in a different method in Java

后端 未结 3 1411
后悔当初
后悔当初 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);
    }
    

提交回复
热议问题