gpt4 book ai didi

java - 使用一个参数搜索数组 - Java

转载 作者:行者123 更新时间:2023-12-01 23:04:45 25 4
gpt4 key购买 nike

我有一个类沙鼠,我创建了一个它的实例数组,并在主方法中进行了正确的初始化。现在我想要一个搜索函数,它只需要一个参数(基本上是搜索字符串)。如何在搜索函数中传递沙鼠数组而不将其作为参数传递。

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];
}

在main方法中声明gerbil类数组

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);
}

最佳答案

使用此代码在类范围内声明数组(在所有函数之外):

private static Gerbil[] gerbils;

现在,用主函数中的大小对其进行初始化:

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 中)是静态的,因此您必须将数组声明为静态。您可以在这里阅读更多相关信息:http://www.javatpoint.com/static-keyword-in-java

关于java - 使用一个参数搜索数组 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22978039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com