我在完成学校作业时遇到了一些困难,长话短说,我在一个方法中声明了两个局部变量,我需要在方法外部访问这些变量:
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;
}
我必须用不同的方法打印以下字符串:
System.out.println("Height: " + resultFeet + " feet " + resultInches + " inches");
有什么建议么?
谢谢。
您无法访问定义范围之外的局部变量。您需要更改方法返回的内容
首先定义一个容器类来保存结果......
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;
}
}
然后修改方法来创建并返回它......
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)