簡體   English   中英

我如何通過 ArrayList<string> 在 Java 中從一種方法到另一種方法。 變量未初始化錯誤</string>

[英]How do I pass an ArrayList<String> from one method to another in Java. Variable not initialised error

Java編碼新手,請多多包涵。 我正在嘗試將我的方法 getChosenWords(int length) 中保存的 ArrayList selectedWords 傳遞給我的方法 getRandom(int length)。 我需要 ArrayList 所以我可以選擇一個隨機索引並返回一個隨機字符串。

請注意,它沒有在 Class 字段中聲明,我無法更改方法的參數 我必須找到另一種方法來傳遞ArrayList但我不確定如何去做。 單元測試使用這些設置參數,我無法更改參數或字段,因為其他類依賴它們保持不變。

我很確定這是需要更改ArrayList<String> chosenWords;的行目前我有一個錯誤變量未在此行初始化 random.nextInt(chosenWords.size());

有什么建議么?

方法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;  
}

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

顯而易見的解決方案,如果 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);        
}

這樣, selectedWords 將被初始化。

不要在getRandom() function 中接收length作為參數,而是采用 ArrayList。 chosenWordsgetRandom() function 並返回從getRandom() function 接收到的值。

希望有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM