程序从文件中读取文本并在数组上写入相同的单词

时间:2013-10-16 10:46:59

标签: java arrays string if-statement for-loop

我编写了一个代码,用于读取文本中的所有单词,计算所有唯一单词,并编写一个包含所有唯一单词的新数组以及该单词在文本上重复的次数。出于一个原因,当我执行它时,程序将所有单词视为唯一,并且在“if”循环中,所有单词的条件变为“假”。你知道我应该从我的代码中改变什么来使它正确地比较单词吗? 谢谢!

import java.util.*;


class textAnalyzer{

public static void main(String[] args){

    Help hj = new Help();
    hj.metode1(args[0]);
}
}


class Help{
void metode1(String filename){

    In les = new In (filname); //input *.txt file

    int totalWords = 0; // counter with total words from the text
    int uniqueW = 0; //counter with the number of total unique words
    boolean funnet = false;

    String[] word = new String[30835]; //array with each unique word
    int quantity[] = new int[30835]; // array the number of times a unique word is repeated on the text

    while(read.endOfFile() == false) {


        for(int i = 0; i < word.length; i++){
                        String oneWord = read.inWord();
                        totalWords++;

            if(ord[i] == denneOrd){
                found = true;
            }

            if(found){
                quantity[i]++;
                uniqueW++;
            }else{
                word[i] = oneWord;
                }   

        }

        totalWords++
    }

    System.out.println("Number words read: " + totalWords + " number unique words: " + uniqueW);



}

}

4 个答案:

答案 0 :(得分:0)

使用“==”来比较原始数据类型,对于对象,您可以使用equals方法与其他对象进行比较。对于String对象,您可以使用.equalsIgnoreCas()方法忽略大小写。

if(word[i] == denneOrd){   //here you need to change 
    found = true;
}

需要改为

if(word[i].equals(denneOrd)){ 
    found = true;
}

答案 1 :(得分:0)

如果您不想考虑案例,请使用.equals方法或.equalsIgnoreCase,而不是==。

  if(ord[i].equals(denneOrd)){
                found = true;
            }

  if(ord[i].equalsIgnoreCase(denneOrd)){
                found = true;
            }

答案 2 :(得分:0)

将所有单词放入集合中,然后检查集合的大小

How to add an item to a set

然后使用

检查设置的内容

checking size of set

Set具有删除重复项的属性

答案 3 :(得分:0)

您最好使用HashMap执行此任务:

Map<String, Integer> word_counts = new HashMap<String, Integer>();

for (Strign word : words_producer) { 

    Integer count = word_counts.get(word, 0);
    word_counts.put(word, (count == null) ? 1 : count + 1);
}

// Get the set of unique words
Set<String> words = word_counts.keySet();

// Print each word's count
for (String word : words) {
    int count = word_counts.get(word);
    System.out.printf("word: %s, count: %d\n", word, count);
}