完全开发ADT Bag链接实现的类(即LinkedBag,Node)。
在继续之前测试你的课程(调用所有方法)。
我已经为ADT Bag的链接实现开发了类,并且还制作了spellchecker.java
我需要帮助来了解如何使用和实现linkedbag类和我的words.txt文件来解决这个问题。
Dictionary.java
package Bags;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Dictionary {
private int M = 1319; // prime number
final private Bucket[] array;
public Dictionary() {
this.M = M;
array = new Bucket[M];
for (int i = 0; i < M; i++) {
array[i] = new Bucket();
}
}
private int hash(String key) {
return (key.hashCode() & 0x7fffffff) % M;
}
// call hash() to decide which bucket to put it in, do it.
public void add(String key) {
array[hash(key)].put(key);
}
// call hash() to find what bucket it's in, get it from that bucket.
public boolean contains(String input) {
input = input.toLowerCase();
return array[hash(input)].get(input);
}
public void build(String filePath) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
add(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
//
public String[] getRandomEntries(int num) {
String[] toRet = new String[num];
for (int i = 0; i < num; i++) {
// pick a random bucket, go out a random number
Node n = array[(int) Math.random() * M].first;
int rand = (int) Math.random() * (int) Math.sqrt(num);
for (int j = 0; j < rand && n.next != null; j++)
n = n.next;
toRet[i] = n.word;
}
return toRet;
}
class Bucket {
private Node first;
public boolean get(String in) { // return key true if key exists
Node next = first;
while (next != null) {
if (next.word.equals(in)) {
return true;
}
next = next.next;
}
return false;
}
public void put(String key) {
for (Node curr = first; curr != null; curr = curr.next) {
if (key.equals(curr.word)) {
return; // search hit: return
}
}
first = new Node(key, first); // search miss: add new node
}
class Node {
String word;
Node next;
public Node(String key, Node next) {
this.word = key;
this.next = next;
}
}
}
我的问题是我正在调用Hash()来决定将它放入哪个存储桶并执行整个过程。而不是这个我想使用我的linkedbag类的实例来查看我的word.txt文件,如果输入匹配与否则返回输出。