我正在用 Java 編寫一個簡單的腳本,它調用另一個包含我所有信息的類。我將我的信息保存在 Object[] 數組中的被調用類中,并且我計劃調用腳本來獲取該數組?,F在這個函數看起來像這樣。public void tradeShop() { /* *Variables must be initialized in order to call shopTrader *The values are just non-null placeholders and they are *replaced with the same values in the tradeValues Object array. */ String targetName = "NPC Name"; String itemName = "Item Name"; int itemQuantity = 1; int minCoins = 1; int minBuy = 1; boolean stackable = false; Object[] tradeValues = shop.defaultValues; for (int i = 0; i < tradeValues.length; i++) { if(String.class.isInstance(tradeValues[i])) {//String check if(i==0) { //0 is NPC Name targetName = (String) tradeValues[i]; } else if (i==1) { //1 is Item Name itemName = (String) tradeValues[i]; } } else if (Integer.class.isInstance(tradeValues[i])) { //Int check if(i==2) { //2 is Item Quantity itemQuantity = (Integer) tradeValues[i]; } else if (i==3) { //3 is Minimum coins minCoins = (Integer) tradeValues[i]; } else if (i==4) { //4 is the Minimum Buy limit minBuy = (Integer) tradeValues[i]; } } else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check stackable = (Boolean) tradeValues[i]; //5 is the item Stackable } else { //TODO: Implement exception } } //Calls ShopTrader() method shopTrader ShopTrader trade = new ShopTrader(); trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);}我覺得像這樣使用 for 循環不是我遍歷這些對象的正確方法,我不應該為每個變量檢查 i==。它還阻礙我向 shopTrader 方法添加重載,因為我必須為每個重載編寫一個全新的 for 循環。有沒有人有更優雅的解決方案來從這個數組中獲取變量?
1 回答

千萬里不及你
TA貢獻1784條經驗 獲得超9個贊
我認為與其將所有信息存儲在 Object[] 中,不如創建一個新類來充當數據結構,即
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
然后您可以直接訪問信息
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...
添加回答
舉報
0/150
提交
取消