[英]How do I pass an ArrayList<String> from one method to another in Java. Variable not initialised error
New to Java coding, please bear with me. Java编码新手,请多多包涵。 I'm trying to pass my ArrayList chosenWords held in my method getChosenWords(int length) to my method getRandom(int length).我正在尝试将我的方法 getChosenWords(int length) 中保存的 ArrayList selectedWords 传递给我的方法 getRandom(int length)。 I need the ArrayList so I can chose a random index and return a random string.我需要 ArrayList 所以我可以选择一个随机索引并返回一个随机字符串。
Note, it's not declared in the Class fields and I am not able to change the parameters of my methods .请注意,它没有在 Class 字段中声明,我无法更改方法的参数。 I have to find another way to pass the ArrayList
in but I'm unsure how to.我必须找到另一种方法来传递ArrayList
但我不确定如何去做。 The unit test uses these set parameters and I can't change parameters or the fields as other classes rely on them staying the same.单元测试使用这些设置参数,我无法更改参数或字段,因为其他类依赖它们保持不变。
I'm pretty sure this is the line that needs changing ArrayList<String> chosenWords;
我很确定这是需要更改ArrayList<String> chosenWords;
的行and currently I have an error variable not initialised on this line.目前我有一个错误变量未在此行初始化。 random.nextInt(chosenWords.size());
Any suggestions?有什么建议么?
Method1方法1
// Takes strings in ArrayList words and stores strings with char int length to ArrayList chosenWords
public ArrayList<String> getChosenWords(int length) {
ArrayList<String> chosenWords = new ArrayList<>();
for(String word1 : words) {
if(word1.length() == length) {
chosenWords.add(word1);
}
}
return chosenWords;
}
Method2方法2
//Returns a randomly selected string from ArrayList chosenWords
public String getRandom(int length) {
ArrayList<String> chosenWords;
Random random = new Random();
int randomIndex = random.nextInt(chosenWords.size());
return chosenWords.get(randomIndex);
}
The obvious solution, if the OP hasn't used it yet?显而易见的解决方案,如果 OP 还没有使用它?
public String getRandom(int length) {
ArrayList<String> chosenWords = getChosenWords(length);
Random random = new Random();
int randomIndex = random.nextInt(chosenWords.size());
return chosenWords.get(randomIndex);
}
That way chosenWords will be initialized.这样, selectedWords 将被初始化。
Instead of receiving length
as a parameter in the getRandom()
function, take an ArrayList.不要在getRandom()
function 中接收length
作为参数,而是采用 ArrayList。 Pass the arraylist chosenWords
to the getRandom()
function and return the value received from the getRandom()
function.将chosenWords
给getRandom()
function 并返回从getRandom()
function 接收到的值。
Hope that helps.希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.