在Java中的方法范围之外更改变量 [英] Changing a variable outside the scope of a method in Java
问题描述
因此,我正在尝试更改最小和最大猜测值(实际猜测由随机数生成器进行),以阻止程序两次猜测相同的数字.
So I'm trying to change the value of a minimum and maximum guess (with the actual guess being made by a random number generator) in order to stop the program from guessing the same number twice.
我有一个可以进行猜测的方法,但是还尝试设置一个最低和最高的猜测值,当再次使用该方法时,它会发生变化
I have a method that makes a guess but also tries to set a lowest and highest guess which then changes when the method is used again
public static int takestab (int low, int high) {
int estimate;
estimate = (low + (int)(Math.random() * ((high - low) + low)));
if (estimate < number) {
lowestguess = estimate;
}
else if (estimate > number) {
highestguess = estimate;
}
return estimate;
}
此外,这些是我在方法范围之外的变量:
Also, these are the vars I have outside of the method scope:
int lowestguess = 1;
int highestguess = 100;
因此,通过运行该方法,猜测可能为50,而实际数字可能为60.如果是这种情况,则"lowestguess"将变为50,以便函数无法猜测任何低于50的事物.
So by running that method, the guess could be 50 and the actual number could be 60. if that's the case, then "lowestguess" becomes 50 so that the function can't guess any lower than 50.
当我这样尝试时,cmd提示说它找不到匹配的符号.
When I try it this way, the cmd prompt says that it cant find the matching symbol.
有什么想法吗?
推荐答案
问题是lowestguess
是instance
变量,但是您尝试通过static
方法访问.
The problem is that lowestguess
is an instance
variable but your trying to access through a static
method.
选项
- 将lowerGuess作为非基本对象(对象)传递给该方法.
- 使用非静态方法
- 使lowestGuess为静态
通过最低猜想
示例:
public static int takestab(int low, int high, Integer Lowest)
这还允许您根据参考 来更改最低".
This allows you to also make changes to Lowest as it is by reference.
非静态方法
将方法更改为public int takestab(int low, int high)
将LowestGuess更改为静态
在多线程环境中,使用此选项时要小心.
You should be careful in multi-threaded environments with this option.
请参阅:
- http://www.coderanch. com/t/407266/java/java/Static-method-refer-instance-variable
- http://www. xyzws.com/Javafaq/how-does-a-static-method-access-instance-variables/31
- http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
- http://www.coderanch.com/t/407266/java/java/Static-method-refer-instance-variable
- http://www.xyzws.com/Javafaq/how-does-a-static-method-access-instance-variables/31
- http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
最后,如果您在诸如eclipse之类的IDE中进行编程,则会出现错误突出显示,从而使诸如此类的错误变得更加明显.
Finally, if you were programming in an IDE such as eclipse you would have error highlighting in which errors such as this become obvious faster.
这篇关于在Java中的方法范围之外更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!