4

これは非常に単純なはずですが (私はそう思います)、正しく理解できません...:|

タスクは次のとおりです。

ユーザーに入力を求めます。入力は 1 つの単語に分割し、配列に入れる必要があります。すべての単語をカウントする必要があります。等しい単語が存在する場合、それらは出力で「+1」を取得します。最後に、リスト内のカウントされた単語の適切な量を出力したいと思います。最初の 2 つの列は正しくできましたが、同じ単語の単語カウンターが頭を悩ませました。単語が等しいことがわかった場合、生成されたリストに 2 回表示されてはなりません。:!

私は完全な Java 初心者なので、コードの判断にはご注意ください。;)

これまでの私のコードは次のとおりです。

package MyProjects;

import javax.swing.JOptionPane;

public class MyWordCount {
public static void main(String[] args) {

    //User input dialog
    String inPut = JOptionPane.showInputDialog("Write som text here");

    //Puts it into an array, and split it with " ".
    String[] wordList = inPut.split(" ");

    //Print to screen
    System.out.println("Place:\tWord:\tCount: ");

    //Check & init wordCount
    int wordCount = 0;

    for (int i = 0; i < wordList.length; i++) {

        for (int j = 0; j < wordList.length; j++){

            //some code here to compare
            //something.compareTo(wordList) ?

        }

        System.out.println(i + "\t" + wordList[i]+ "\t" + wordCount[?] );
    }

}
}
4

5 に答える 5

6

ハッシュマップを使用してそれを行うことができます。ハッシュマップにはキーと値のペアが格納され、各キーは一意である必要があります。

したがって、あなたの場合、キーは分割した文字列の単語になり、値はカウントになります。

入力を単語に分割して文字列配列に入れたら、最初の単語をキーとして Hashmap に入れ、値として 1 を入れます。後続の単語ごとに、関数 containsKey() を使用して、その単語をハッシュマップ内の既存のキーのいずれかと一致させることができます。true が返された場合は、そのキーの値 (カウント) を 1 つ増やします。そうでない場合は、単語と 1 を新しいキーと値のペアとして Hashmap に入れます。

于 2012-09-11T21:12:21.090 に答える
2

したがって、2 つの文字列を比較するには、次のようにします。

String stringOne = "Hello";
String stringTwo = "World";
stringOne.compareTo(stringTwo);
//Or you can do
stringTwo.compareTo(stringOne); 

コメントのように文字列を文字列配列と比較することはできません。この文字列配列の要素を取得し、それを比較する必要があります (つまり、stringArray[要素番号])。

単語の数をカウントするために、繰り返される単語の数を決定する場合は、整数の配列が必要になります (したがって、新しい int[] を作成します)。new int[] の各場所は、単語の配列内の単語に対応する必要があります。これにより、単語が繰り返される回数を数えることができます。

于 2012-09-11T21:07:35.003 に答える
1
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;

import javax.swing.JOptionPane;

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {

    //Print to screen
    System.out.println("Place:\tWord:\tCount: ");

    //User input dialog
    String inPut = JOptionPane.showInputDialog("Write som text here");

    //Puts it into an array, and split it with " ".
    String[] wordList;
    try{
        wordList = inPut.split(" ");
    }catch(PatternSyntaxException e) {
        // catch the buggy!
        System.out.println("Ooops.. "+e.getMessage());
        return;
    }catch(NullPointerException n) {
        System.out.println("cancelled! exitting..");
        return;
    }

    ArrayList<String> allWords = new ArrayList<String>();
    for(String word : wordList) {
        allWords.add(word);
    }

    // reset unique words counter
    int uniqueWordCount = 0;

    // Remove all of the words
    while(allWords.size() > 0) {
        // reset the word counter
        int count = 0;

        // get the next word
        String activeWord = allWords.get(0);

        // Remove all instances of this word
        while(doesContainThisWord(allWords, activeWord)) {
            allWords.remove(activeWord);
            count++;
        }

        // increase the unique word count;
        uniqueWordCount++;

        // print result.
        System.out.println(uniqueWordCount + "\t" + activeWord + "\t" + count );

    }

}

/**
 * This function returns true if the parameters are not null and the array contains an equal string to newWord.
 */
public static boolean doesContainThisWord(ArrayList<String> wordList, String newWord) {
    // Just checking...
    if (wordList == null || newWord == null) {
        return false;
    }

    // Loop through the list of words
    for (String oldWord : wordList) {
        if (oldWord.equals(newWord)) {
            // gotcha!
            return true;
        }
    }
    return false;
}

}
于 2012-09-11T21:31:12.057 に答える
1

テキスト内の単語の位置を記録し、それをカウントとして使用する WordInfo オブジェクトのマップを使用したソリューションを次に示します。LinkedHashMap は、キーが最初に入力されたときのキーの順序を保持するため、単にキーを反復するだけで「出現順にキャスト」できます。

すべてのキーを小文字として格納し、元の大文字と小文字を WordInfo オブジェクトに格納することで、最初に出現したときの大文字と小文字を保持しながら、この大文字と小文字を区別しないようにすることができます。または、すべての単語を小文字に変換してそのままにしておきます。,分割する前に、最初のテキストからすべての/ ./などを削除することを検討することも"できますが、とにかく完全にはなりません。

import java.util.LinkedHashMap;
import java.util.Map;

import javax.swing.JOptionPane;

public class MyWordCount {
    public static void main(String[] args) {

        //User input dialog
        String inPut = JOptionPane.showInputDialog("Write som text here");

        Map<String,WordInfo> wordMap = new LinkedHashMap<String,WordInfo>();

        //Puts it into an array, and split it with " ".
        String[] wordList = inPut.split(" ");

        for (int i = 0; i < wordList.length; i++) {
            String word = wordList[i];
            WordInfo wi = wordMap.get(word);
            if (wi == null) {
                wi = new WordInfo();            
            }
            wi.addPlace(i+1);
            wordMap.put(word,wi);           
        }

        //Print to screen

        System.out.println("Place:\tWord:\tCount: ");

        for (String word : wordMap.keySet()) {          

            WordInfo wi = wordMap.get(word);        
            System.out.println(wi.places() + "\t" + word + "\t" + wi.count());
        }

      }
}

そして WordInfo クラス:

import java.util.ArrayList;
import java.util.List;

public class WordInfo {

    private List<Integer> places;

    public WordInfo() {
        this.places = new ArrayList<>();
    }

    public void addPlace(int place) {
        this.places.add(place);
    }


    public int count() {
        return this.places.size();
    }

    public String places() {
        if (places.size() == 0)
            return "";

        String result = "";
        for (Integer place : this.places) {
            result += ", " + place;
        }
        result = result.substring(2, result.length());
        return result;
    }
}
于 2012-09-11T22:57:24.660 に答える
0

助けてくれてありがとう。-これは私がやったことです:

import java.util.ArrayList;

import javax.swing.JOptionPane;

public class MyWordCount {
public static void main(String[] args) {

    // Text in
    String inText = JOptionPane.showInputDialog("Write some text here");

    // Puts it into an array, and splits
    String[] wordlist = inText.split(" ");

    // Text out (Header)
    System.out.println("Place:\tWord:\tNo. of Words: ");

    // declare Arraylist for words
    ArrayList<String> wordEncounter = new ArrayList<String>();
    ArrayList<Integer> numberEncounter = new ArrayList<Integer>();

    // Checks number of encounters of words
    for (int i = 0; i < wordlist.length; i++) {
        String word = wordlist[i];

        // Make everything lowercase just for ease...
        word = word.toLowerCase();

        if (wordEncounter.contains(word)) {
            // Checks word encounter - return index of word
            int position = wordEncounter.indexOf(word);
            Integer number = numberEncounter.get(position);
            int number_int = number.intValue();
            number_int++;
            number = new Integer(number_int);
            numberEncounter.set(position, number);

            // Number of encounters - add 1;
        } else {
            wordEncounter.add(word);
            numberEncounter.add(new Integer(1));
        }

    }

    // Text out (the list of words)
    for (int i = 0; i < wordEncounter.size(); i++) {
        System.out.println(i + "\t" + wordEncounter.get(i) + "\t"
                + numberEncounter.get(i));
    }

  }
}
于 2012-09-21T23:11:08.567 に答える