亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Java 中高效地循環遍歷具有多種變量類型的對象數組

在 Java 中高效地循環遍歷具有多種變量類型的對象數組

阿晨1998 2023-01-05 16:54:45
我正在用 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();

...


查看完整回答
反對 回復 2023-01-05
  • 1 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號