当前在游戏中,它会询问某些问题,例如,您是否已收集了所有钥匙,杀死了所有老板等?
但是,当它接近结尾时,它会问“您想使用哪个密钥?”。它做得很好,但是一旦到达“门”部分,它实际上并没有获得键的值,它只会输出0
主要代码
public static int possibleKey()
{
SetnGet sng = new SetnGet();
int keys;
do
{
System.out.println("Which key would you like to use?");
keys = in.nextInt();
}
while(keys != 1 && keys != 2 && keys != 3);
return keys;
}
public static int possibleLevel()
{
SetnGet sng = new SetnGet();
System.out.println("Which door would you like to enter? - 1, 2, 3 or 4");
int level;
if(sng.accessibleKey() == 3)
{
do
{
System.out.println("You have all three keys, you have complete access");
level = in.nextInt();
}
while(level != 1 && level != 2 && level != 3);
}
else
{
do
{
System.out.println("You have no level access");
level = in.nextInt();
}
while(level != 1 && level != 2 && level != 3 && level != 4);
}
return level;
}
设置并从SetnGet类获取
private int possibleKey;
private int possibleLevel;
public int setPossibleKey()
{
return possibleKey;
}
public void setPossibleKey(int possibleKey)
{
this.possibleKey = possibleKey;
}
public int getPossibleLevel()
{
return possibleLevel;
}
public void setPossibleLevel(int possibleLevel)
{
this.possibleLevel = possibleLevel;
}
最佳答案
方法possibleLevel()
创建SetnGet
类(SetnGet sng = new SetnGet();
)的实例,然后,立即读取实例(int
)的类型sng.accessibleKey()
的字段。这样读取的结果当然为0,因为这是int
类字段的默认值,并且您从未为该字段设置任何其他值。结果,您总是转到else
并看到“您没有级别访问权限”消息。
解决该问题的方法是将SetnGet sng = new SetnGet();
从possibleLevel()
移至该类,然后确保将possibleKey()
调用的结果设置为该值,如下所示:
public class Main {
private static Scanner in = new Scanner(System.in);
private static SetnGet sng = new SetnGet();
public static void main(String[] args) {
int selectedKey = possibleKey();
sng.accessibleKey(selectedKey);
int level = possibleLevel();
}
public static int possibleKey() {
// your initial implementation of the method
}
public static int possibleLevel() {
// your initial implementation of the method, but
// without the "SetnGet sng = new SetnGet();" line
}
}
SetnGet
类如下所示:class SetnGet {
private int accessibleKey;
int accessibleKey() {
return accessibleKey;
}
void accessibleKey(int accessibleKey) {
this.accessibleKey = accessibleKey;
}
}
这将解决您的最初问题。然后,您可以考虑对代码进行进一步的重构,例如,使用方法参数(而不是共享的类字段)在方法之间传递数据,还摆脱
SetnGet sng = new SetnGet();
方法中的冗余possibleKey()
行,等等。