[英]How to use a method from another class
我想添加這個方法(它位於我的 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);
}
}
}
}
到這個班級(ghetto 班級,這是我的主要班級)
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() 未定義。
您需要為Houses
類添加一個默認構造函數。
在房屋類中:
public Houses() {
}
您可能有一個,看看您的類,您可能使用 netBeans 或 Eclipse 自動生成它,因此它將所有類屬性作為參數。
看看OOP原理:
A類房子
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
}
如您在其他問題中提供的代碼所示, Houses
的構造函數是:
public Houses(int size, int blue, int red) { ... }
它需要這三個參數,因此您必須提供它們,它們似乎是方形房屋網格邊的大小以及藍色和紅色房屋的初始數量。 所以也許:
Houses h = new Houses(5, 3, 3);
h.step();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.