[英]How can I reference / define an array from another method in java?
我有一些类似于以下代码:
public class exampleClass {
public void main(){
defineVariable();
nextMethod();
}
void nextMethod(){
list[8] = "threw away";
}
void defineVariable(){
String[] list = {"trivial string","more trivial strings",
"just another trivial string","tr","a","sd",
"godzilla","ate","my","pony","and homework","trivial"};
}
}
而且我无法访问nextMethod中的列表。如何解决此问题,将这样的小数组全局化似乎很琐碎,但实际的数组却成百上千个(因此,我没有c + p我的实际代码,尽管至少我不会介意的)。
非常感谢,并且附带说明,这是在Android中,尽管我怀疑这会影响Java代码(我是否认为这是错误的?)。
无论如何再次感谢! 我最近一直在大量使用StackOverflow,但只做了一点贡献,所以从现在开始,我将尝试回答尽可能多的问题。
谢谢,
只需在课堂上声明即可。
public class exampleClass {
public void main()
{
nextMethod(defineVariable());
}
void nextMethod(String[] list)
{
list[8] = "threw away";
}
private String tab[] defineVariable()
{
String[] list= {"trivial string","more trivial strings","just another trivial string","tr","a","sd",
"godzilla","ate","my","pony","and homework","trivial"};
return list
}
}
如果让defineVariable为void并在其自己的范围内创建一个变量,则该变量在完成执行后便会消失。 而是让defineVariable返回列表,然后将此列表用作nextMethod()函数的参数。
一种存储许多变量的巧妙方法是将它们分组为不同的对象。 这样,可以将相关变量放入同一个对象,并且将主类中的变量数量减少到可管理的数量。
在下面的示例中,我将变量设为public。 如果愿意,可以代替创建getter和setter。
public class Actions {
public String humans[] = { "sit", "stand", "eat", "walk", "run", "drive", ride" };
public String dogs[] = { "sit", "stand", "bark", "run" };
public String sharks[] = { "swim", "attack" };
}
public class Equipment {
public String armour[] = { "leather", "chainmail", "plate" };
public String weapon[] = { "sword", "axe", "dagger" };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.