[英]Java: trouble with Scanner / ArrayList types
上下文:我對編碼非常陌生。 我正在寫一個基於文本的單人RPG作為一種學習方法。
因此,我有一個ArrayList用來存儲Item類的對象。 我想根據來自掃描儀的用戶輸入,檢查ArrayList是否存在某個項目(Item類中的對象)。
如果可能的話,我認為如果將Item傳遞給開關(基於用戶輸入),而不是我后來不得不對其進行“翻譯”以使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);
}
}
}
預先感謝您的回答。
表達式的類型必須為char,byte,short,int,Character,Byte,Short,Integer,String或枚舉類型(第8.9節),否則會發生編譯時錯誤。
來自http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11
這意味着您不能將項目本身傳遞到交換機中。 但是,如果您想擁有可讀的代碼(對於其他團隊成員而言),或者在小組中工作,則可以使用哈希映射和枚舉進行切換。
例如:
public enum ItemChoice {
SWORD, WAND, CAT
}
然后是哈希圖
HashMap<String, ItemChoice> choice = new HashMap<String, ItemChoice>();
然后,使用所需的值加載哈希圖,例如:
choice.put("Wand", ItemChoice.WAND)
然后,您可以輕松地從用戶輸入中獲取枚舉值,然后在開關中使用它。 它比您當前檢查字符串的方法更廣泛,但是它更具可讀性,您可以將其稱為“更干凈”。
如果您使用當前的方法,請檢查Strings。 然后,我建議您從字符串itemChoice中刪除“”空格,這樣就不必處理大小寫 ,例如:
case "testwand":
case "test wand":
但是您只需要一個案例
case "testwand":
這實際上並沒有影響任何事情,但是由於您不再使用布爾值has,因此您可以執行此操作
if(newInvTest.contains(testWand)){
// the interaction occurs
// boolean has is not needed anymore!
}
關於未來的建議,您可能想要創建一個Player對象,這樣就可以將ArrayList保留在player對象中,而不是靜態變量中。 而且,它可以讓您輕松輕松地從播放器中保存數據,例如播放器的金錢數量,擊殺次數,關卡數量等。最好堅持遵循面向對象的編程。
因此,例如,您將擁有:
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。 因此,您可以這樣獲得庫存:
player.getInventory();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.