我在学校作业中遇到了一点困难,长话短说,我在方法中声明了两个局部变量,我需要在方法外部访问这些变量:
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);
}
不能从方法 B 中的方法 A 访问局部变量。这就是为什么他们是本地人。 看一看:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
因此,局部变量仅对它们所在的方法可见 被声明;他们无法从班级的其他成员访问。
我建议使用@MadProgrammer编写的解决方案 - 创建包含feet
和inches
的类。
你需要创建一个共享变量来保存你的结果,或者你将结果封装在一个对象中,然后返回到调用者方法,它可能像result
public class Result {
public final int resultFeet;
public final int resultInches;
public Result(int resultFeet, int resultInches) {
this.resultFeet = resultFeet;
this.resultInches = resultInches;
}
}
现在,你做出一个结果,
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);
}
在其他函数中使用此结果来打印结果。
Result result = convertHeightToFeetInches(<your_input>);
System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")