簡體   English   中英

如何在JAVA中檢查字符串數組中的相等單詞

[英]How to check for equal words in string array in JAVA

這應該很簡單(我認為),但我無法做到正確......:|

任務如下:

詢問用戶一些輸入。 必須將輸入拆分為單個單詞並放入數組中。 應該計算所有單詞。 如果存在相等的單詞,則它們在輸出上得到“+1”。 最后,我想打印出來,並希望列表中有適當數量的計算單詞。 我的前兩列是正確的,但是平等的話語讓我頭疼。 如果發現一個單詞是相同的,它在生成的列表中不能出現兩次!

我是一個完整的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[?] );
    }

}
}

您可以使用Hashmap來執行此操作。 Hashmap存儲鍵值對,每個鍵必須是唯一的。

所以在你的情況下,一個鍵將是你已經拆分的字符串的一個單詞,值將是它的計數。

將輸入拆分為單詞並將其放入字符串數組后,將第一個單詞(作為鍵)放入Hashmap中,將1作為值。 對於每個后續單詞,您可以使用函數containsKey()將該單詞與Hashmap中的任何現有鍵進行匹配。 如果它返回true,則將該鍵的值(count)遞增1,否則將word和1作為新的鍵值對放入Hashmap中。

因此,為了比較兩個字符串,您可以:

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

您不能像在評論中那樣將String與String數組進行比較。 你必須在這個字符串數組中取一個元素,然后比較它(So stringArray [elementNumber])。

要計算有多少單詞,如果要確定重復單詞的數量,則需要有一個整數數組(所以創建一個新的int [])。 new int []中的每個位置都應對應於單詞數組中的單詞。 這將允許您計算單詞重復的次數。

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

}

這是一個使用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;
    }
}

謝謝你試圖幫助我。 - 這就是我最終做的事情:

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

  }
}

暫無
暫無

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

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