语境:我很新的编码。我正在编写一个基于文本的单人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);
}
}
}
非常感谢您的回答。
如何使用HashMap代替? –
你可以覆盖'Item'的'equals'。 –
标题不清楚,问题是键入开关.... – AxelH