如何使用另一个类的方法

时间:2014-03-30 18:09:59

标签: java

我想添加此方法(位于我的Houses类中)

public void step() {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            // Who are my neighbors
            House[][] ns = neighbors(houses[i][j]);

            // How many are red, blue
            int countRed = 0;
            int countBlue = 0;
            for (int n = 0; n < 8; n++) {
                if (ns[j][j].who == HouseType.Red) {
                    countRed = countRed + 1;
                }
                if (ns[j][j].who == HouseType.Blue) {
                    countBlue = countBlue + 1;
                }
            }
            // Decide to stay or move
            if (houses[i][j].decide(countRed, countBlue)) {
                houses[i][j].move(ns);
            }
        }
    }
}

到这个班级(贫民窟班是我的主要班级)

    startButton = new JButton("start");
    add(startButton);
    startButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a timer
            time = new javax.swing.Timer((int) (1000 * deltaT), this);
            time.start();
            // Add a listener for the timer - which is the step method
            if (e.getSource() == time) 
            {
                Houses h = new Houses();
                h.step();
                //Houses.step();
            }

        }
    });

所以我想要的是在我的主类ghetto中使用step方法(位于我的Houses类中),这里它给出了错误:

           Houses h = new Houses();
           h.step();

它表示构造函数Houses()未定义。

2 个答案:

答案 0 :(得分:0)

您需要为Houses类添加默认构造函数。

在房屋类:

public Houses() {

}

您可能有一个,看看您的类,您可能使用netBeans或Eclipse自动生成它,因此它将所有类属性作为参数。

看看OOP原则:

班级

public class House {
    int numberOfPeopleInHouse = 2;
    int numberOfDog = 0;

    public House() {
        //default constructor does nothing but creating a house.
    }
    public House(int dogCount) {
        this.numberOfDog = dogCount;
        /* This particular constructor take a int as parameter, and instead of creating
         * a simple house, we create an house with a modified dog count.
         */
    }
    public void addPeople(int numberOfPeople) {
        this.numberOfPeopleInHouse = this.numberOfPeopleInHouse + numberOfPeople;
    }
}

在你的主要

static void main(string[] args) {
    House firstHouse = new House(1);
    //firstHouse contains 2 people and 1 dog

    House secondHouse = new House();
    //secondHouse contains 2 people and 0 dog

    secondHouse.addPeople(2);
    //secondHouse contains 4 people and 0 dog
}

答案 1 :(得分:0)

your other question中提供的代码所示,Houses的构造函数为:

public Houses(int size, int blue, int red) { ... }

它期望这三个参数,所以你必须提供它们,看起来像是方形房子网格边的大小,以及蓝色和红色房屋的初始数量。也许吧:

Houses h = new Houses(5, 3, 3);
h.step();
相关问题