📄 dictionarywithvector.java
字号:
import java.util.*;
import java.io.*;
/**
* This class models a dictionary
*
* @author author name
* @version 1.0.0
*/
public class DictionaryWithVector {
/* Standard output stream */
private static PrintWriter stdOut =
new PrintWriter(System.out, true);
/* Standard error stream */
private static PrintWriter stdErr =
new PrintWriter(System.err, true);
/* Words in the dictionary */
private Vector words;
/**
* Tests the implementation of class <code>Dictionary</code>.
*
* @param args not used.
*/
public static void main(String[] args) {
DictionaryWithVector dictionary = new DictionaryWithVector();
String[] knownWords = {"host", "computer", "house", "dog",
"cat", "world", "book", "money", "river",
"paper", "coffee"};
String[] unknownWords = {"maison", "haus", "casa"};
for (int i = 0; i < knownWords.length; i++) {
dictionary.addWord(knownWords[i]);
}
for (int i = 0; i < knownWords.length; i++) {
if (! dictionary.hasWord(knownWords[i])) {
stdErr.println("** Test failure, " +
"word not found in the dictionary: " +
knownWords[i]);
}
}
for (int i = 0; i < unknownWords.length; i++) {
if (dictionary.hasWord(unknownWords[i])) {
stdErr.println("** Test failure, " +
"non dictionary word found in dictionary: "
+ unknownWords[i]);
}
}
Vector result = dictionary.getStartsWith("ho");
if (! (result.size() == 2 && result.contains("host")
&& result.contains("house"))) {
stdErr.println("** Test failure in getStartsWith()");
}
stdOut.println("done");
}
/**
* Creates an empty dictionary.
*/
public DictionaryWithVector() {
words = new Vector();
}
/**
* Adds a new word to this dictionary.
*
* @param word the word to be added.
*/
public void addWord(String word) {
words.add(word);
}
/**
* Returns <code>true</code> if the specified word is part of
* this dictionary.
*
* @param word the word to be looked for.
* @return <code>true</code> if the specified word is part of
* this dictionary; <code>false</code> otherwise.
*/
public boolean hasWord(String word) {
return words.contains(word);
}
/**
* Returns a vector of all words in this dictionary that start
* with the specified prefix.
*
* @param prefix the prefix.
* @return a <code>Vector</code> of all words in this dictionary
* that start with the specified prefix.
*/
public Vector getStartsWith(String prefix) {
Vector result = new Vector();
for (Iterator i = words.iterator() ; i.hasNext(); ) {
String word = (String) i.next();
if (word.startsWith(prefix)) {
result.add(word);
}
}
return result;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -