使用数组传递参数?

时间:2013-11-26 14:53:56

标签: java arrays class parameters

我在这里使用27个不同对象的参数;代码片段如下:

//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");

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

1 个答案:

答案 0 :(得分:0)

你可以这样做:

    // 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并将它们存储到数组中。您可以对其他对象类型执行相同操作,然后传递数组。