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.
解决方案
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);
}