簡體   English   中英

程序從文件中讀取文本並在數組上寫相等的單詞

[英]Program to read a text from file and write equal words on an array

我編寫了一個代碼,該代碼從文本中讀取所有單詞,對所有唯一單詞進行計數,並編寫一個包含所有唯一單詞以及單詞在文本上重復的次數的新數組。 由於執行該程序的一個原因,該程序將所有單詞視為唯一,並且在“ if”循環上,所有單詞的條件變為“ false”。 您知道我應該對我的代碼進行哪些更改以使其正確地比較單詞嗎? 謝謝!

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);



}

}

使用“ ==”比較原始數據類型,對於對象,您可以使用equals方法與其他對象進行比較。 對於String對象,可以使用.equalsIgnoreCas()方法忽略大小寫。

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

需要更改為

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

如果不想考慮大小寫,請使用.equals方法或.equalsIgnoreCase ,而不要使用==。

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

要么

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

將所有單詞放在集合中,然后檢查集合的大小

如何將項目添加到集合中

然后使用檢查設置的大小

檢查組的大小

集具有刪除重復項的屬性

您最好使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM