2016-03-26 69 views
-1

什么我工作在一个文件中读取并将它传递给我已经有这个做一个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 
+4

你实际上没有解释发生了什么问题。 – elhefe

+1

*“我不完全确定我在哪里迷路”*同上。我们也失败了,因为不清楚你试图做什么不同于你已经做的。我的意思是,它不能像*“追加星号的”*部分一样简单,因为字符串连接很容易。 – Andreas

+2

为什么你要在返回值中加上括号? 'return'后没有空格。使它看起来像一个方法调用。 'return wholePhrase;'和'return phrase;'是你应​​该怎么做的。 – Andreas

回答

1

从对问题的意见,你说你叫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 

这样做的原因是,getPhrase需要一个ArrayList<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的实例并从该实例调用该方法。

+0

谢谢你的解释。现在对我来说更有意义。我现在应该能够解决这个问题 – CamronT

0

两个问题。

  1. Java中的返回语句遵循'返回变量名';'而不是方法类型的调用。
  2. 由于索引从零开始,因此您应该使用随机数减1来获取数组列表。
+3

至于#2,'nextInt(int)'返回从零开始的数字。 – Andreas

0

然后只是做getPhrase(readInPhrase())。编译器将调用getPhrase(),然后在堆栈跟踪返回点位于getPhrase(...)处对readInPhrase()进行蒸发。这将返回ArrayList(顺便说一句,需要用<String>进行类型参数化)。然后,以ArrayList作为参数调用getPhrase(),然后获得该短语,然后有很多欢乐。

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

相关问题