简体   繁体   中英

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. I'm trying to pass my ArrayList chosenWords held in my method getChosenWords(int length) to my method getRandom(int length). I need the ArrayList so I can chose a random index and return a random string.

Note, it's not declared in the Class fields and I am not able to change the parameters of my methods . I have to find another way to pass the ArrayList in but I'm unsure how to. 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;and currently I have an error variable not initialised on this line. random.nextInt(chosenWords.size());

Any suggestions?

Method1

// 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

//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?

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.

Instead of receiving length as a parameter in the getRandom() function, take an ArrayList. Pass the arraylist chosenWords to the getRandom() function and return the value received from the getRandom() function.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM