我试图找到一种方法来玩“ longestword”游戏,由于二进制排序树,我基本上从输入文件到输出文件的字母数组中提取单词。我在下面找到了一个看起来还不错的小程序。
但是我遇到了方法“ getAlpha”的问题,据说该方法在特殊情况下使用,因为它会在读取前跳过所有非字母,而不仅仅是跳过空白字符。在程序中没有提到它,我现在也不怎么写它了。
// ------------------主程序------------------------ ------------
static TreeNode root; // Points to the root of the binary sort
// tree that holds the words. At the
// beginning of the program, when the tree
// is empty, root is null.
public static void main(String[] args) {
TextReader in; // A stream for reading from the input file.
PrintWriter out; // A stream for writing to the output file.
String inputFileName; // Input file name, specified by the user.
String outputFileName; // Output file name, specified by the user.
root = null; // Start with an empty tree. (Not really necessary,
// since null is the default initial value anyway.)
/* Get the input file name from the user and try to create the
input stream. If there is a FileNotFoundException, print
a message and terminate the program. */
TextIO.put("Input file name? ");
inputFileName = TextIO.getln().trim();
try {
in = new TextReader(new FileReader(inputFileName));
}
catch (FileNotFoundException e) {
TextIO.putln("Can't find file \"" + inputFileName + "\".");
return;
}
/* Get the output file name from the user and try to create the
output stream. If there is an IOException, print a message
and terminate the program. */
TextIO.put("Output file name? ");
outputFileName = TextIO.getln().trim();
try {
out = new PrintWriter(new FileWriter(outputFileName));
}
catch (IOException e) {
TextIO.putln("Can't open file \"" + outputFileName + "\" for output.");
TextIO.putln(e.toString());
return;
}
/* Read all the words from the input stream and insert them into
the array of words. Reading from a TextReader can result in
an error of type TextReader.Error. If one occurs, print an
error message and terminate the program. */
try {
while (true) {
// Skip past and non-letters in the input stream. If an
// end-of-stream has been reached, end the loop. Otherwise,
// read a word and insert it into the array of words.
while ( ! in.eof() && ! Character.isLetter(in.peek()) )
in.getAnyChar();
if (in.eof())
break;
insertWord(in.getAlpha()); `**the required method**`
}
}
catch (TextReader.Error e) {
TextIO.putln("An error occurred while reading from the input file.");
TextIO.putln(e.toString());
return;
}