【发布时间】:2014-12-10 02:56:16
【问题描述】:
我有一个类,SpellCheck,它(连同其他各种东西)根据交互窗口中给出的文件名创建一个 trie。例如,当我输入 java SpellCheck small.txt 时,我知道创建了一个词典/字典,因为它是由 SpellCheck 中的其他方法显示的。
public class SpellCheck{
// the dictionary
private LexiconTrie dict;
// Constructor; creates window elements
public SpellCheck(String[] files) {
dict = new LexiconTrie(files);
我需要在我的其他类 LexiconTrie 中访问该 LexiconTrie dict(迭代、根、节点等)中的信息。但是,每当我尝试访问它时(即使使用 SpellCheck.dict,它也会给我“dict 在 SpellCheck 中具有私有访问权限”的错误(或类似的内容)。
在这种情况下,我是否没有完全理解私有/公共类的交互? (如果我没有提供足够的信息,请告诉我) ----------编辑/更新---------
这是拼写检查中的方法
public void doAutoComplete() {
Collection<String> arr = dict.getCompletions(curText.trim().toLowerCase(), num_value);
String intro = "Up to " + num_value + " completions";
display(arr, "No matches found", intro);
}
我需要在 LexiconTrie 中编写方法getCompletions()。我的教授为我们实现了一个 GUI 界面。此 GUI 界面创建一个搜索栏,每当用户在搜索栏中键入字母时,该搜索栏就会调用 doAutoComplete。在 LexiconTrie 中,我应该写 getCompletions 以返回在 LexiconTrie dict 中找到的匹配项(“完成”)(这是在 SpellCheck 中私下创建和存储的)。
我看到按照以下思路编写方法:
// Method you have to implement
public Collection<String> getCompletions(String lowerCase, int max) {
String searchWord = lowerCase;
int maxReturned = max;
LinkedList trieMatches = new LinkedList();
// this is as far as I got, it won't even print the search word.
// I get an error from trying to look into dict with .containsWord
if (dict.containsWord(searchWord)){
System.out.println(searchWord);
//add word/prefix to LinkedList
//add all children and their children up until max#
}
else{
return null;
}
}
【问题讨论】:
-
好吧,
private字段是私有的。它们不能在课堂外访问。这正是 private 的用途。 -
我认为你确实不了解 private/public.. private 成员只能在他们自己的类中访问。
-
在
SpellCheck类中为其提供某种public访问器/获取器 -
您需要阅读有关访问修饰符的信息,请查看此内容。 docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
-
我并没有真正关注你。我猜你应该写
LexiconTrie?LexiconTrie将有自己的私有变量以及私有和公共方法,LexiconTrie中的方法可以直接访问它们,使用this.field或通常只是field。您的LexiconTrie没有理由查看SpellCheck中的任何内容,甚至不应该知道存在SpellCheck这样的东西。