【发布时间】:2014-09-28 04:29:54
【问题描述】:
我想将输入存储在我的字典类中,以便我可以在该类中搜索单词。但我还需要在其他类中使用数组。有谁知道如何将输入添加到我的 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());
}
}
【问题讨论】:
-
您在哪个班级访问数组列表时遇到问题?
-
我希望能够在另一个名为 FindWords 的类中使用 dict ArrayList。但是,我要么无法引用该字典,要么它打印为一个空列表。
-
您的 FindWords 类中可能存在一些问题。更好地显示该代码
-
这是 FindWords 的代码,无论我的原始类中的列表是什么,它都会返回一个空列表。公共类:FindWords { public static void main(String[] args) { Dictionary dictionary = new Dictionary(); System.out.print(dictionary.getList()); }
-
您正在创建一个全新的 Dictionary 类实例。所以没有机会得到你之前在字典中插入的字符串。
标签: java arrays eclipse arraylist