我想檢查某個String
是否在我的TreeSet
中。當它應該返回true時,TreeSet返回false?
它返回false
當它應該返回true
,但我不知道我在哪裏搞砸了我的代碼。下面是代碼:
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
但是進入的話「車」在上面的代碼中,「巡邏」和「老鼠」的時候,它會返回「假」,從dict.contains(word)
而且所有三個上面的字,是我.txt文件。
你有什麼想法出了什麼問題?如果您需要更多我的代碼,我會編輯它,請讓我知道。
編輯:有時,當我嘗試猜測某些單詞時,它返回true,但大多數時候它返回false(dict.contains())。
編輯2:添加了我所有的代碼。
哪一個返回false? 'include'還是當前的代碼? – Dadani
作爲準則,發佈重現錯誤所需的最小代碼量。 – flakes
我也好奇'sort'在這裏做什麼 – flakes