在Java中以其他方法使用局部声明的变量 [英] Using local declared variables in a different method in Java
本文介绍了在Java中以其他方法使用局部声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做作业时遇到了一些困难,长话短说,我在一个方法中声明了两个局部变量,我需要在方法之外访问这些变量:
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");
有什么建议吗?
谢谢.
推荐答案
您不能在定义的范围之外访问局部变量.您需要更改方法返回的值
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);
}
这篇关于在Java中以其他方法使用局部声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文