如何将ArrayList方法传递给同一类中的不同方法



我正在处理的是读取一个文件并将其传递给ArrayList,我已经用这个完成了:

public ArrayList readInPhrase() {
    String fileName = "wholephrase.txt";
    ArrayList<String> wholePhrase = new ArrayList<String>();
    try {
        //creates fileReader object
        FileReader inputFile = new FileReader(fileName);
        //create an instance of BufferedReader
        BufferedReader bufferReader = new BufferedReader(inputFile);
        //variable to hold lines in the file
        String line;
        //read file line by line and add to the wholePhrase array
        while ((line = bufferReader.readLine()) != null) {
            wholePhrase.add(line);
        }//end of while
        //close buffer reader
        bufferReader.close();
    }//end of try
    catch(FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Unable to open file '" +
                fileName + " ' ", "Error", 
                JOptionPane.INFORMATION_MESSAGE, null);
    }//end of file not found catch
    catch(Exception ex) {
        JOptionPane.showMessageDialog(null, "Error while reading in file '" 
                + fileName + " ' ", "Error", 
                JOptionPane.INFORMATION_MESSAGE, null);
    }//end of read in error
    return wholePhrase;
}//end of readInPhrase

我现在遇到的问题是,我想浏览这个ArrayList,然后从中随机选择一个短语,最终添加星号到所选短语的一部分。我尝试了各种不同的方法来做到这一点。

这是我最后一次尝试:

public String getPhrase(ArrayList<String> wholePhrase) {
    Random random = new Random();
    //get random phrase
    int index = random.nextInt(wholePhrase.size());
    String phrase = wholePhrase.get(index);
    return phrase;
    }//end of getPhrase

根据对问题的评论,您说您正在调用getPhrase,如下所示:

HangmanPhrase.getPhrase()

这导致错误

method getPhrase in class HangmanPhrase cannot be applied to given types;
required: ArrayList<String> found: no arguments reason:
   actual and formal argument lists differ in length

原因是getPhraseArrayList<String>作为自变量:

public String getPhrase(ArrayList<String> wholePhrase) {

您需要将ArrayList传递给方法getPhrase,如下所示:

ArrayList<String> myListOfStrings = new ArrayList<String>();
// do stuff with myListOfStrings
getPhrase(myListOfStrings);

此外,由于getPhrase是一个实例方法,而不是静态方法,因此不能通过HangmanPhrase.getPhrase调用它。您需要创建HangmanPhrase的一个实例,并从该实例中调用该方法。

就我所见,有两个问题。
  1. Java中的Return语句跟在"Return variable name;"后面而不是方法类型调用
  2. 您应该使用随机数减去1来获得数组列表,因为索引从零开始

然后执行getPhrase(readInPhrase())。编译器将调用getPhrase(),然后用getPhrase(...)处的堆栈跟踪返回点来计算readInPhrase()。这将返回ArrayList(顺便说一下,需要使用<String>对其进行类型参数化)。然后,以ArrayList为参数调用getPhrase(),然后得到短语,然后大家都很高兴。

此外,readInPhrase()需要返回一个ArrayList<String>(在Java 1.5+中)

最新更新