📄 dictionary.java
字号:
import java.io.*;
/**
* This class models a dictionary
*
* @author author name
* @version 1.0.0
*/
public class Dictionary {
/* Standard output stream */
private static PrintWriter stdOut =
new PrintWriter(System.out, true);
/* Standard error stream */
private static PrintWriter stdErr =
new PrintWriter(System.err, true);
/* Initial size of the array */
private static final int INITIAL_SIZE = 5;
/* Words in the dictionary */
private String[] words;
/* Indicates the next available location in the array */
private int nextIndex;
/**
* Tests the implementation of class <code>Dictionary</code>.
*
* @param args not used.
*/
public static void main(String[] args) {
Dictionary dictionary = new Dictionary();
String[] knownWords = {"desk", "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]);
}
}
stdOut.println("done");
}
/**
* Creates an empty dictionary.
*/
public Dictionary() {
words = new String[INITIAL_SIZE];
nextIndex = 0;
}
/**
* Adds a new word to this dictionary.
*
* @param word the word to be added.
*/
public void addWord(String word) {
if (nextIndex >= words.length) {
// creates a new array, which is twice the size
// of the current array
String[] biggerWords = new String[2 * words.length];
// copies the contents of the current array
// into the new array
for (int i = 0; i < words.length; i++) {
biggerWords[i] = words[i];
}
words = biggerWords;
}
words[nextIndex] = word;
++nextIndex;
}
/**
* 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) {
for (int i = 0; i < nextIndex; i++) {
if (words[i].equals(word)) {
return true;
}
}
return false;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -