【发布时间】:2014-08-14 21:08:34
【问题描述】:
这个想法很简单:
- 将文本文件加载到字符串中。
- 将此字符串拆分为多个段落。
- 将所有段落拆分为单词。
- 将每个单词添加到 ArrayList。
结果是一个包含文本文件中所有单词的 ArrayList。
程序有效;它可以很好地加载 ArrayList 中的所有单词。
但是,在 ArrayList 中查找特定项目的任何“IF”语句都不起作用。
除了:如果单词是换行符。
public String loadText(String resourceName){
// Load the contents of a text file into a string
String text = "";
InputStream stream = FileIO.class.getResourceAsStream(resourceName);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String str = "";
try {
while ((str = reader.readLine())!=null){
text += str + "\n";
}
} catch (Exception e) {
System.out.println("Unable to load text stream!");
}
return text;
}
public void test(){
ArrayList<String> collectionOfWords = new ArrayList<String>();
String text = loadText("/assets/text/intro.txt");
// Split into paragraphs
String paragraphs[] = text.split("\n");
for (String paragraph: paragraphs){
// Split into words
String words[] = paragraph.split(" ");
// Add each word to the collection
for (String word: words){
collectionOfWords.add(word);
}
// Add a new line to separate the paragraphs
collectionOfWords.add("\n");
}
// Test the procedure using a manual iterator
for (int i=0; i<collectionOfWords.size(); i++){
// ===== WHY DOES THIS WORK?
if (collectionOfWords.get(i)=="\n")
System.out.println("Found it!");
// ===== BUT THIS DOESN'T WORK???
if (collectionOfWords.get(i)=="test")
System.out.println("Found it!");
// NOTE: Same problem if a I use:
// for (String word: collectionOfWords){
// if (word=="test")
// System.out.println("Found it!");
}
}
文本文件示例: 快速布朗\n 狐狸跳过\n 测试懒狗\n
有什么想法吗?我现在只是从头开始我的设计并尝试一些完全不同的东西......
【问题讨论】:
标签: java string if-statement arraylist