2017-11-25 71 views
1

目前在遊戲中,它會問某些問題,如你收集了所有的鍵,殺死所有的老闆等。 但是,當它關閉到結尾,並要求「你想用哪個鍵?「。它確實是好的,但一旦得到它的門部分,它實際上並沒有拿到鑰匙的價值,它只是輸出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; 
} 
+0

Did you逐步執行IDE調試器中的代碼?你發現了什麼? –

+0

我發現每次運行IDE調試器時都會測試每一位數據。它從sng.accessibleKey到System.out.println(「你沒有級別訪問」); – Questionable

回答

3

方法possibleLevel()創建SetnGet類(SetnGet sng = new SetnGet();)和,之後其的一個實例,讀取實例(sng.accessibleKey())的int類型的字段。這樣讀取的結果當然是0,因爲這是int類字段的默認值,並且您從不爲您的字段設置任何其他值。因此,你總是去else並看到「你沒有級別訪問」的信息。

可以做些什麼來解決這個問題是從possibleLevel()移動SetnGet sng = new SetnGet();的類,然後確保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; 
    } 
} 

這將解決您最初的問題。然後,您可以考慮進一步重構代碼,例如,使用方法參數(而不是共享類字段)在方法之間傳遞數據,也可以從possibleKey()方法中刪除多餘的SetnGet sng = new SetnGet();行。