Home > Blockchain >  How do I pass an ArrayList<String> from one method to another in Java. Variable not initialise
How do I pass an ArrayList<String> from one method to another in Java. Variable not initialise

Time:09-08

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related