有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用数组传递参数?

我在这里使用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) 个答案

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