2017-02-10 57 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

好吧,非常感谢您的帮助帮帮我! –