我想将输入存储在我的字典类中,以便我可以搜索此类中的单词。但我也需要在其他类中使用该数组。有没有人有我如何添加输入到我的Dictionary()构造函数的想法?如何在多个类中使用数组列表?
有没有人有如何解决这个问题的想法?
非常感谢你提前!!!!
public class Dictionary {
// Private data fields
public ArrayList<String> dict;
Dictionary() {
dict = new ArrayList<String>();
}
public void add (String s){
dict.add(s);
}
public int size(){
return dict.size();
}
public String get(int i) {
return dict.get(i);
}
public ArrayList<String> getList(){
return dict;
}
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.print("Must have a file.");
System.exit(1);
}
try {
File dictionaryFile = new File(args[0]);
Scanner fin = new Scanner(dictionaryFile);
System.out.println(dictionaryFile.getAbsolutePath());
if (!dictionaryFile.exists()) {
System.out.println("Dictionary " + args[0] + "does not exist");
}
else if (!dictionaryFile.canRead()) {
System.out
.println("Dictionary " + args[0] + " cannot be read.");
}
Dictionary dict = new Dictionary();
while (fin.hasNext()) {
dict.add(fin.nextLine());
}
for (int i = 0; i < dict.size(); i++) {
System.out.println(dict.get(i));
}
} catch (FileNotFoundException e) {
System.out.println("No such file found " + args[0]);
}
}
}
/**
*This is the class I want to reference the array in
*/
public class FindWords {
public static void main(String[] args) {
Dictionary dictionary = new Dictionary();
System.out.print(dictionary.getList());
}
}
在哪个班,你所面临的麻烦访问ArrayList中之前修改您的findwords类如下
}
后? – 2014-09-28 04:34:14
我希望能够在另一个名为FindWords的类中使用字典ArrayList。但是,我要么无法引用该词典,要么将其打印为空列表。 – Theodore 2014-09-28 04:38:25
可能在您的FindWords类中存在一些问题。更好地显示代码 – 2014-09-28 04:43:23