2017-02-10 52 views
0

語境:我很新的編碼。我正在編寫一個基於文本的單人RPG作爲學習方法。的Java:用掃描儀/ ArrayList的類型麻煩

所以,我有我使用存儲類產品的對象的ArrayList。我想基於從掃描儀用戶輸入檢查(從項目類對象)項目存在的ArrayList中。如果可能的話,我認爲如果我將一個項目傳遞給交換機(基於用戶輸入)而不是一個字符串,我稍後必須「翻譯」ArrayList才能使用它。

這可能嗎?或者我必須按照我在下面的代碼中寫出的方式來完成它?或者,有沒有更好的,完全不同的方式去實現它,我不知道?

public class Test{ 

//New Array that will store a player's items like an inventory 

static ArrayList<Item> newInvTest = new ArrayList<>(); 

//Placing a test item into the player's inventory array 
//The arguments passed in to the constructor are the item's name (as it would be displayed to the player) and number of uses 

static Item testWand = new Item("Test Wand", 5); 

//Method for when the player wants to interact with an item in their inventory 

public static void useItem(){ 
    System.out.print("Which item do you wish to use?\n: "); 
    Scanner scanner5 = new Scanner(System.in); 
    String itemChoice = scanner5.nextLine(); 
    itemChoice = itemChoice.toLowerCase(); 
    switch (itemChoice){ 
     case "testwand": 
     case "test wand": 
     boolean has = newInvTest.contains(testWand); 
     if(has == true){ 
      //the interaction occurs 
     }else{ 
      System.out.println("You do not possess this item: " + itemChoice); 
     } 
    } 
} 

非常感謝您的回答。

+1

如何使用HashMap代替? –

+0

你可以覆蓋'Item'的'equals'。 –

+0

標題不清楚,問題是鍵入開關.... – AxelH

回答

0

類型中表達的必須是char,字節,短型,整型,字符,字節,短,整數,字符串,或枚舉類型(§8.9),或編譯時會出現誤差。

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11

這意味着你無法通過項目本身到交換機。但是,如果你想有可讀的代碼,也許對你的其他團隊成員,如果你是一個組的工作,那麼你可以使用交換機一個HashMap和枚舉。

例如:

public enum ItemChoice { 
    SWORD, WAND, CAT 
} 

再來說HashMap的

HashMap<String, ItemChoice> choice = new HashMap<String, ItemChoice>(); 

然後,你與你所期望的值,如加載到散:

choice.put("Wand", ItemChoice.WAND) 

然後你可以很容易地從用戶輸入中獲得枚舉值,然後在交換機中使用它。它比你目前的檢查字符串的方式更廣泛,但它是更具可讀性,你可以把它稱爲「清潔劑」。

如果你與你目前的做法去,用繩子檢查。那麼我會建議你從字符串itemChoice刪除「」空的空間所以你不必你做的情況下,如:

case "testwand": 
case "test wand": 

而是你只需要一個案例

case "testwand": 

這是不是真的影響什麼,但你以後不要再使用布爾有,那麼你可以這樣做

if(newInvTest.contains(testWand)){ 
    // the interaction occurs 
    // boolean has is not needed anymore! 
} 

並建議˚F還是未來,你可能要創建一個Player對象,這樣你可以保持在選手對象ArrayList中,而不是一個靜態變量。此外,它可以讓你輕鬆地從播放器,保存數據更容易,如金錢的玩家數量,殺敵,層數等數......這只是不如試試堅持面向對象的編程。

因此,例如,你會:

public class Player { 

    private ArrayList<Item> newInvTest = new ArrayList<>(); 

    private String name; 

    private int currentLevel; 

    public String getName(){ 
     return name 
    } 

    public int getCurrentLevel(){ 
     return currentLevel 
    } 

    public ArrayList<Item> getInventory(){ 
     return newInvTest; 
    } 

} 

所以,如果你想購買的廣告,你可以參考的實例變量,而不是一個靜態變量。將這些變量分配給Player對象更有意義,因爲它們屬於玩家。所以你可以得到像這樣的庫存:

player.getInventory(); 
+0

您可以詳細說明如何保存數據的工作原理,以及如何讓玩家作爲類的對象(而不是像我一樣擁有靜態變量的類它現在)會有幫助嗎? –

+0

如果你指的是玩家屬性的數據保存。我發佈了一個關於Player類如何幫助組織和保持不同值的解釋。您可能還想閱讀:http://stackoverflow.com/questions/14284246/is-there-a-reason-to-always-use-objects-instead-of-primitives – Pablo

+0

好吧,非常感謝您的幫助幫幫我! –