【发布时间】:2012-04-28 09:44:35
【问题描述】:
不要担心哈希表的人,只要告诉我一些如何管理字符串的想法。
我需要使用哈希表对用户在字典中输入的单词进行拼写检查。我从哈希表中得到了一个名为 checkDictionary() 的方法来检查给定的单词是否存在于字典中。如果单词存在则返回布尔值,否则返回 false。
我想做的是,我只是想在拼写错误的时候检查字典中的单词,做一些可能的更正。
可能的更正:
更改一个字母:例如,如果拼错的单词是“kest”,我想尝试所有可能的 一次更改一个字符,然后在字典中查找修改后的单词。这 可能性将是“aest”、“best”、...、“zest”、“kast”、...、“kzst”等。
---我怎样才能一次改变一个字符,并且从a到z。
交换相邻的字母:例如,如果拼错的单词是“ebst”,尝试“best”,esbt” 和“ebts”。
---我怎样才能改变相邻的字母,需要交换什么的?..
删除一个字母:例如,如果拼写错误的单词是 “tbird”,尝试一次删除一个字母的所有可能性,并查找修改后的单词 在字典中,分别是:“bird”、“tird”、“tbrd”和“tbir”。
---如何每次都删除每个字母?
请记住,输入的单词可以是任意长度。
我需要在检查字典中的单词后将此建议返回给用户。 字符串中是否有任何方法可以用来实现这些功能。 请帮助实施上述更改、交换和删除方法。
import java.util.*;
import java .io.*;
public class HashTableDemo
{
public static void main(String [] args)
{
// constructs a new empty hashtable with default initial capacity
HashTable hashtable = new HashTable();
Scanner keyboard = null;
Scanner input=null;
try
{
System.out.println("Enter a word to check in dictionary");
keyboard = new Scanner(System.in);
String word = (keyboard.nextLine().toUpperCase());
//Adding aal dictionary words from a text file to hash table.
input=new Scanner(new FileInputStream("TWL.txt"));
int i=1;
// adding value into hashtable
while(input.hasNextLine())
{
String hello = input.nextLine();
hashtable.put( hello, new Integer(i) );
i++;
}
);
if(hashtable.checkDictionary(word))
System.out.println("The word "+word+" is there in the dictionary.");
else
System.out.println("The word "+word+" is not there in the dictionary.");
}//try
//Here I need to implement the required methods if the word is not in dictionary and misspelled.
catch(FileNotFoundException e)
{
System.out.println("Cannot open file");
System.exit(0);
}//end catch
【问题讨论】:
-
那么您只是在寻找如何操作字符串?阅读 java.lang.String 上的 API 文档。
-
首先,格式化并修复您的代码。它甚至不编译并且看起来很糟糕。此外,您不能在 try 块的结尾和 catch 块的开头之间放置任何内容...