我有一个类沙鼠,我已经在main方法中正确初始化了它的实例数组。现在我想要一个只需要一个参数(基本上是搜索字符串)的搜索功能。如何在搜索功能中传递沙鼠阵列而不将其作为参数传递。
public class Gerbil {
String lab_id;
String name;
boolean isBite;
public int[] eat;
public Gerbil(int x) {
eat = new int[x];
}
public String getLab_id() {
return lab_id;
}
public void setLab_id(String lab_id) {
this.lab_id = lab_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isBite() {
return isBite;
}
public void setBite(boolean isBite) {
this.isBite = isBite;
}
public void setEat(int a, int b) {
eat[a]=b;
}
public int getEat(int a){
return eat[a];
}
主方法中的沙鼠类数组的声明
Gerbil[] gerbils = new Gerbil[gerbil_no];
// initializing the Food class into the Gerbil Class
for (int x = 0; x < gerbils.length; x++) {
gerbils[x] = new Gerbil(types);
}
答案 0 :(得分:3)
使用此代码在类范围内声明数组(在所有函数之外):
private static Gerbil[] gerbils;
现在,在主函数中使用size初始化它:
gerbils = new Gerbil[gerbil_no];
所以,最后,你的课程看起来像这样:
public class Gerbil
{
private static Gerbil[] gerbils;
public static void main(String[] args) {
// write code here to read the array size into gerbil_no
// then initialize your array with size here
gerbils = = new Gerbil[gerbil_no];
for (int x = 0; x < gerbils.length; x++) {
gerbils[x] = new Gerbil(types);
}
// continue with your code
}
}
注意:在Java中,静态函数只能访问静态成员。由于main函数(在Java中)是静态的,因此必须将数组声明为static。您可以在此处详细了解:http://www.javatpoint.com/static-keyword-in-java
答案 1 :(得分:0)
在你的主要课程中:
private static Gerbil[] gerbils;
public static void main(String[] args) {
// initializing the Food class into the Gerbil Class
gerbils = = new Gerbil[gerbil_no];
for (int x = 0; x < gerbils.length; x++) {
gerbils[x] = new Gerbil(types);
}
}
因为你在静态main函数中使用变量,所以你必须在变量声明中使用static modifier。
答案 2 :(得分:0)
把它放在另一个班级:
class Gerbil {
String lab_id;
String name;
boolean isBite;
public int[] eat;
public Gerbil(int x) {
eat = new int[x];
}
public String getLab_id() {
return lab_id;
}
public void setLab_id(String lab_id) {
this.lab_id = lab_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isBite() {
return isBite;
}
public void setBite(boolean isBite) {
this.isBite = isBite;
}
public void setEat(int a, int b) {
eat[a]=b;
}
public int getEat(int a){
return eat[a];
}
}
class Y {
private static final int gerbil_no = 0;
Gerbil[] gerbils = new Gerbil[gerbil_no];
void foo() {
// initializing the Food class into the Gerbil Class
for (int x = 0; x < gerbils.length; x++) {
gerbils[x] = new Gerbil(10 /* You had types here */);
gerbils[x].setName("Hello");
}
}
Boolean search (String str) {
for (int i = 0, length = gerbils.length; i < length; i++)
if (gerbils[i].name.compareTo(str) == 0)
return true;
return false;
}
}