【发布时间】:2016-04-23 03:55:49
【问题描述】:
我想检查某个String 是否在我的TreeSet 中。
它应该返回true 时返回false,但我不确定我的代码哪里搞砸了。代码如下:
HashSet<String> dict = new HashSet<String>();
//TreeSet<String> dict = new TreeSet<String>(dicty); //snabbare såhär?
int ranNum;
String randomWord;
public AngloTrainer(String dictionaryFile) throws IOException {
loadDictionary(dictionaryFile);
System.out.println(dict.size() + " words loaded from dictionary.txt ");
Random randNumb = new Random();
ranNum = (randNumb.nextInt(6) + 4);
//randomWord = randomLetters(ranNum);
randomWord = "carpatrol";
System.out.println("The random letters are: " + randomWord);
Scanner reader = new Scanner(System.in);
System.out.println("Guess a word!");
//System.out.println(dict.contains("car"));
//System.out.println(dict.contains("patrol"));
//System.out.println(dict.contains("rat"));
while(reader.hasNextLine() != false){
String gWord = reader.next();
if(includes(sort(randomWord), sort(gWord))){
if(dict.contains(gWord)){
System.out.println("ok!");
}else{
System.out.println("not ok!");
}
}else{
System.out.println("not ok!");
}
}
//reader.close();
}
private String sort(String s){
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}
private void dumpDict() {
for(String word: dict){
System.out.println(word);
}
}
private void loadDictionary( String fileName ) throws IOException{
BufferedReader bufRead = new BufferedReader(new FileReader(new File(fileName)));
while(bufRead.readLine() != null){
dict.add(bufRead.readLine());
}
//bufRead.close();
}
private String randomLetters( int length ) {
Random randomGenerator = new Random();
String letters = "aabcdeefghiijklmnoopqrstuuvwxyyz";
StringBuffer buf = new StringBuffer(length);
for ( int i = 0; i < length; i++ )
buf.append( letters.charAt(randomGenerator.nextInt(letters.length())));
return buf.toString();
}
private boolean includes( String a, String b ) {
if ( b == null || b.length() == 0 )
return true;
else if ( a == null || a.length() == 0 )
return false;
//precondition: a.length() > 0 && b.length() > 0
int i = 0, j = 0;
while ( j < b.length() ) {
if (i >= a.length() || b.charAt(j) < a.charAt(i))
return false;
else if (b.charAt(j) == a.charAt(i)) {
i++; j++;
} else if (b.charAt(j) > a.charAt(i))
i++;
}
//postcondition: j == b.length()
return true;
}
include() 方法工作正常,它比较两个字符串以查看其中一个中的字母是否包含在另一个中。
include("car"); //returns true
include("patrol"); //returns true
include("rat"); //returns true
但是当在上面的代码中输入“car”、“patrol”和“rat”时,它会从dict.contains(word)返回“false”
以上三个词都在我的 .txt 文件中。
您有什么想法吗?如果您需要更多我的代码,我会编辑它,请告诉我。
编辑:有时当我尝试猜测一些单词时,它返回 true,但大多数时候它返回 false (dict.contains())。
EDIT2:添加了我所有的代码。
【问题讨论】:
-
哪个返回false?
include还是当前代码? -
作为准则发布重现错误所需的最少代码量。
-
我也很好奇
sort在这里做什么 -
我还会检查
loadDictionary是否加载了您期望它加载的内容。 TreeSet 不太可能与简单的字符串成为问题的原因。 -
@CarltonJr.,逻辑思考一下。标准 JDK 库经受无数用户和测试失败的概率是多少?
标签: java algorithm data-structures treeset