Alan Alan - 21 days ago 5
Java Question

How to use an enhanced for loop to iterate through a HashSet that is in another method?

For my assignment I have been asked to produce the following:


  • Creates a
    HashMap<String,Integer>

  • Loops over all the words returned by
    getWordArray()
    and puts each word into the
    HashMap
    with the number of times it occurs

  • Returns
    HashMap<String, Integer>



I have already created a HashSet inside another method called
getWordArray()
but I am struggling to figure out how to make it so that the for loop iterates through the
getWordSet()
method without getting an error "
non-static
method cannot be referenced from a static context". When I am string to return my
HashSet
which was created, I am getting the error "incompatible types:

HashMap<String, Integer>
cannot be converted to String".

Here is the code:

WordGroup class

import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;

public class WordGroup {

String word;

//Creates constructor which stores a string value in variable "word" and converts this into lower case using the lower case method.
public WordGroup(String aString) {
this.word = aString.toLowerCase();
}
public String[] getWordArray() {
String[] wordArray = word.split("-");
return wordArray;
}


public Set<String> getWordSet(WordGroup secondWordGroup) {

HashSet<String> newHashSet = new HashSet<>();

for (String word : secondWordGroup.getWordArray())
newHashSet.add(word);

for (String word : this.getWordArray())
newHashSet.add(word);
System.out.println(newHashSet);
return newHashSet;

}
public String getWordCounts()
{
HashMap<String, Integer> myHashMap=new HashMap<String, Integer>();
int loopcounter = 0;
for (WordGroup it : WordGroup.getWordArray())

loopcounter = loopcounter +1;
myHashMap.add(it);
return myHashMap;
}
}


Main class

public class Main{
public static void main (String[] args) {
WordGroup firstWordGroup = new WordGroup("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");

}


I have two main queries:


  • How do I correctly iterate over the getWordArray method?

  • How do I return HashMap of data types as opposed to being a String?



I cannot see any static methods being used in my WordGroup class so obviously I have some misunderstanding of static somewhere and I understand the second error, I'm just not too sure on how to fix it.

Thanks in advance.

Edit: I have tried using this if statement:

public Set<String> getWordCounts(WordGroup secondWordGroup)
{
HashMap<String,Integer> myMap;

if (myMap.keySet().contains(getWordArray[i]))
{
myMap.get(getWordArray[i]) +1;
}
else
{
myMap.put(getWordArray[i],1);

}
return myMap;
}


I'm not sure if it is done right but there are multiple errors?

Answer

First of All: HashSet cannot have duplicate values in it. Let say HashSet already has word 'hello' in it. then add('hello') does nothing. HashSet still have only one word 'hello' there. Use ArrayList instead, if you need to have multiple 'hello' there.

Second where did you find HashMap.add() method? it is not there.

Third: did you cut some pieces of your code?

for (WordGroup it : WordGroup.getWordArray())

 loopcounter = loopcounter +1;

That for loop does only loopcounter = loopcounter +1;

nothing else.

Go this way: HasMap has a key as word and value as number of occurencies i.e.

HasMap<String,Integer> myMap

then when you go through your wordArray (you do not need anything else)

If myMap has a key wordArray[i] increase value associated with it in the map:

myMap.put(wordArray[i],myMap.get(wordArray[i]) +1)

else put new element

myMap.put(wordArray[i],1)

I hope you will write other things around it on your own.

EDITED:

public class WordGroup {

    String  word;

    // Creates constructor which stores a string value in variable "word" and converts this into lower case using
    // the lower case method.
    public WordGroup(String aString) {

        this.word = aString.toLowerCase();
    }

    public String[] getWordArray() {

        String[] wordArray = word.split("-");
        return wordArray;
    }

    public HashMap<String, Integer> getWordCountsMap() {

        HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();

        for (String nextWord: this.getWordArray()) {
            if (myHashMap.keySet().contains(nextWord)) {
                myHashMap.put(nextWord, myHashMap.get(nextWord) + 1);
            } else {
                myHashMap.put(nextWord, 1);
            }

        }

        return myHashMap;
    }
}

end better to do not create HashMap each time, but do it once in constructor.

    public class WordGroup {

    String  word;
    HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();

    // Creates constructor which stores a string value in variable "word" and converts this into lower case using
    // the lower case method.
    public WordGroup(String aString) {

        this.word = aString.toLowerCase();
        this.createWordCountsMap();
    }

    public String[] getWordArray() {

        String[] wordArray = word.split("-");
        return wordArray;
    }

    public HashMap<String, Integer> getWordCountsMap()
    {
        return this.myHashMap;
    }

    private void createWordCountsMap() {

        for (String nextWord : this.getWordArray()) {
            if (this.myHashMap.keySet().contains(nextWord)) {
                this.myHashMap.put(nextWord, this.myHashMap.get(nextWord) + 1);
            } else {
                this.myHashMap.put(nextWord, 1);
            }
        }
    }
}
Comments