Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for equal words in string array in JAVA

This should be quite simple (I think), but I just can't get it right...:|

The task is as follows:

Ask the user for some input. The input must be split in to single words and put into an array. All words should be counted. If equal words exists, they get a "+1" on the output. Finally I want to print out and hopefully the right amount of counted words in a list. I got the first two columns right, but the word-counter of equal words gave me a headache. If a word is found to be equal, it mustnt appear twice in the generated list! :!

I am a complete JAVA newbie so please be kind on the code-judging. ;)

Here is my code so far:

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[?] );
    }

}
}
like image 370
CustomCase Avatar asked Dec 27 '22 18:12

CustomCase


2 Answers

You can use Hashmap to do that. A Hashmap stores key-value pairs and each key has to be unique.

So in your case, a key will be a word of the string you have split and value will be it's count.

Once you have split the input into words and put them into a string array, put the first word,as a key, into the Hashmap and 1 as it's value. For each subsequent word, you can use the function containsKey() to match that word with any of the existing keys in the Hashmap. If it returns true, increment the value (count) of that key by one, else put the word and 1 as a new key-value pair into the Hashmap.

like image 150
Quasar Avatar answered Dec 30 '22 10:12

Quasar


So in order to compare two strings, you do:

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

You can't compare a String to a String array like in your comment. You would have to take an element in this string array, and compare that (So stringArray[elementNumber]).

For counting how many words there are, if you are determining the number of repeated words, you would want to have an array of integers (So make a new int[]). Each place in the new int[] should correspond to the word in your array of words. This would allow you to count the number of times a word is repeated.

like image 27
Clark Avatar answered Dec 30 '22 11:12

Clark