我是Java的新手,我不太明白当我尝试调用方法时,为什么会出现NoSuchMethodError。基本上,我尝试在另一个名为Agent.java的文件中调用一个方法,该文件又使用WordList.java中的方法。
public class DiscussionDirector{
public static void main(String args[]){
Agent ag = new Agent();
ag.generateAgent();// line5: This line is problematic.
}
public static void discuss(){
}
}
这是错误:
java.lang.NoSuchMethodError: WordList.buffR(Ljava/lang/String;)Ljava/util/ArrayList;
at Agent.generateAgent(Agent.java:152)
at DiscussionDirector.main(DiscussionDirector.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
以下是Agent.java的第148行:
public static void generateAgent(){
...
try{
if(gender == "male"){
wl.buffR("MaleNames.txt");// line 148: I'm using a method in another file called WordList.java
name = wl.getRandomWord();
}
else{
wl.buffR("FemaleNames.txt");
name = wl.getRandomWord();
}
}
catch (IOException e){
if(gender == "male"){
name = "Rejean";
}
else{
name = "Ginette";
}
}
...
}
这是我的WordList.java
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
import java.io.FileNotFoundException;
public class WordList{
private static Random r = new Random();
private static ArrayList<String> words =new ArrayList<String>();
public static void main(String[] args) throws IOException {
String filename = "Majors.txt";
WordList wl = new WordList();
buffR(filename);
System.out.println(words);
System.out.println(getRandomWord());
}
public static ArrayList buffR(String filename) throws IOException {
// this is the method concerned, basically it reads words from a file and add it to an ArrayList.
words.clear();//clear ArrayList from previous readings.
String line = null;
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
while (( line = br.readLine()) != null){
words.add(line);
}
br.close();
return words;
}
public static String getRandomWord(){ //method that retrieves randomly a string from the ArrayList
WordList wl = new WordList();
String randomWord;
if(words.size() > 1){
int index = r.nextInt(words.size());
randomWord = words.get(index);
}
else{
randomWord = "Unable to read file: Cities.txt";
}
return randomWord;
}
}