【发布时间】:2014-12-08 23:38:35
【问题描述】:
我有一个数组,正在从文本文件中读取一系列单词。我要做的是,如果扫描仪所在的当前单词不在数组中,则将其添加到数组中。如果该单词已经在数组中,则转到下一个单词并再次开始该过程 - 检查它是否在数组中,如果没有则添加它,依此类推。问题是我加载了一个单词 abc,它不在数组中,所以我添加了它。然后我加载另一个单词 x,它不在数组中,所以我添加它。然后我尝试再次加载 abc,它已经在数组中,但无论如何它都会被添加。我的代码需要更改哪些内容?
try {
fileScanner = new Scanner(inFile).useDelimiter("[ ,!?.0123456789]+");
System.out.println("The input has been loaded successfully.");
while (fileScanner.hasNext()) {
currentWord = fileScanner.next().toUpperCase();
// If the word is not found, add it to the array.
if (ht.findWord(currentWord, ht.array) == false) {
ht.fillTable(currentWord, ht.asciiSum(currentWord), ht.array);
} else {
// if the word is found, move on to the next word.
break;
}
}
fileScanner.close();
} // end try
catch (Exception e) {
System.out.println("The input file has not been successfully loaded.");
}
public boolean findWord(String word, String[] table) {
boolean found = false;
for (int i = 0; i < table.length; i++) {
if (table[i] == word) {
found = true;
//System.out.println("The word " + word + " was found at " + table[i]);
} else {
found = false;
}
}
return found;
}
【问题讨论】:
-
比较两个字符串 table[i] == word 的错误方式。你必须使用 equals()
标签: java arrays search boolean lookup