【问题标题】:Passing parameters in using an array?使用数组传递参数?
【发布时间】:2013-12-11 19:02:09
【问题描述】:

我在这里使用了 27 个不同对象的参数;一个sn-p的代码如下:

//start of Region1
static ToEat region1EatOption2 = new ToEat("Maggie Mays","www.Maggiemays.co.uk","£££");
static ToEat region1EatOption3 = new ToEat("Villa Italia","www.VillaItalia.co.uk","££££");

static ToShop region1ShopOption2 = new ToShop("Deja vu","www.dejavubelfast.co.uk","£££");
static ToShop region1ShopOption3 = new ToShop("Rio Brazil","www.Riobrazil.co.uk","£££££");

static ToParty region1PartyOption1 = new ToParty("The M Club","www.Mclub.co.uk","£");
static ToParty region1PartyOption2 = new ToParty ("Queens Student Union","www.qubsu.co.uk","£££");
static ToParty region1PartyOption3 = new ToParty ("The Eglantine Inn","www.egbar.co.uk","£££££");
//end of Region 1

static Specials region1Specials1 = new Specials("The Eglantine Inn","6 shots = £6");
static Specials region1Specials2 = new Specials ("Deja vu" , "15% Student discount");
static Specials region1Specials3 = new Specials ("Viva Italia", "2 Course meal for £10");

这似乎是一个很长的参数传递方式。有没有办法可以使用数组来获取这些信息,然后使用数组来传递参数?

【问题讨论】:

  • 您可以使用数组和 CSV 文件来存储值。读入值,用逗号分隔,然后将它们传递给对象数组。

标签: java arrays class parameters


【解决方案1】:

你可以这样做:

    // declare your ToEat-Entries here
    String[][] edibleEntries = new String[][] {
            {"Maggie Mays", "www.Maggiemays.co.uk", "£££"},
            {"Villa Italia","www.VillaItalia.co.uk","££££"},
            ...
        };

    // this creates an array containing the above entries
    ToEat[] edibles = new ToEat[edibleEntries.length];
    for(int i = 0; i < edibleEntries.length; i++) {
        edibles[i] = new ToEat(edibles[i][0], edibles[i][1], edibles[i][2]);
    }

字符串数组包含每个条目的 3 个字符串,循环从这些条目创建 ToEat-Objects 并将它们存储到一个数组中。您可以对其他对象类型执行相同操作,然后传递数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2022-08-03
    相关资源
    最近更新 更多