目前在游戏中,它会询问某些问题,例如,你收集了所有的钥匙,杀死了所有的老板等。 但是当它接近结束时它会询问“你想使用哪个键?”。它做得很好,但一旦到达门部分,它实际上并没有得到键的值,它只输出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;
}
Set和Get来自SetnGet Class
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;
}
答案 0 :(得分:3)
方法possibleLevel()
创建SetnGet
类(SetnGet sng = new SetnGet();
)的实例,然后读取实例类型int
的字段{{1} }})。这种读取的结果当然是0,因为这是sng.accessibleKey()
类字段的默认值,您永远不会为您的字段设置任何其他值。因此,您总是转到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();
行等等。