So I am trying to complete this code. The goal is to input an array of strings, then count the frequency of how often the words are found. For example:
input:
joe
jim
jack
jim
joe
output:
joe 2
jim 2
jack 1
jim 2
joe 2
An array must be chosen for Strings, and another array much be chosen for word frequency.
My code so far:
I am stuck into trying to implement this. The string method is set, but how am I going to count the frequency of words, and also assign those values to an array. Then print both side by side. I do know that once the integer array is set. We can simply do a for loop to print the values together such as. System.out.println(String[i] " " countarray[i]);
public class LabClass {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int freq = 0;
for (int i = 0; i < listSize; i ) {
if (wordsList[i].compareTo(currWord) == 0) {
freq ;
}
}
return freq;
}
public static void main(String[] args) {
LabClass scall = new LabClass();
Scanner scnr = new Scanner(System.in);
// assignments
int listSize = 0;
System.out.println("Enter list Amount");
listSize = scnr.nextInt();
// removing line to allow input of integer
int size = listSize; // array length
// end of assignments
String[] wordsList = new String[size]; // string array
for (int i = 0; i < wordsList.length; i ) { //gathers string input
wordsList[i] = scnr.nextLine();
}
for (int i = 0; i < listSize; i ) {
String currWord = wordsList[i];
int freqCount = getFrequencyOfWord(wordsList, listSize, currWord);
System.out.println(currWord " " freqCount);
}
}
}
CodePudding user response:
int some_method(String[] arr, String word) {
int count = 0;
for (int i=0; i<arr.size(); i ) {
if (arr[i].equals(word)) count ;
}
return count;
}
Then in main method:
String[] array = ["joe", "jake", "jim", "joe"] //or take from user input
int[] countArray = new int[array.size()]
for (int i=0; i<array.size(); i ) {
countArray[i] = some_method(array, array[i])
}
System.out.println(array[0] " " countArray[0]);
Ouput: joe 2
CodePudding user response:
public class LabClass {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter list Amount: ");
String[] words = new String[scan.nextInt()];
System.out.println("Enter words:");
for (int i = 0; i < words.length; i )
words[i] = scan.nextLine();
Map<String, Long> histogram = calculateFrequency1(words);
histogram.forEach((word, count) -> System.out.println(word ' ' count));
}
public static Map<String, Long> calculateFrequency1(String[] words) {
return Arrays.stream(words).collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
}
public static Map<String, Long> calculateFrequency2(String[] words) {
Map<String, Long> histogram = new HashMap<>();
for (String word : words)
histogram.put(word, histogram.getOrDefault(word, 0L) 1);
return histogram;
}
}