語境:我很新的編碼。我正在編寫一個基於文本的單人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