我正在研究的是读取一个文件并将其传递给我已经完成的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
答案 0 :(得分: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
的实例并从该实例调用该方法。
答案 1 :(得分:0)
据我所见,有两个问题。
答案 2 :(得分:0)
然后做getPhrase(readInPhrase())
。编译器将调用getPhrase()
,然后使用readInPhrase()
处的堆栈跟踪返回点评估getPhrase(...)
。这将返回ArrayList
(顺便说一句,需要使用<String>
进行类型参数化)。然后,以getPhrase()
作为参数调用ArrayList
,然后你得到短语,然后有很多欢乐。
此外,readInPhrase()
需要返回ArrayList<String>
(在Java 1.5 +中)