Java Dictionary Searcher - java

I am trying to implement a program that will take a users input, split that string into tokens, and then search a dictionary for the words in that string. My goal for the parsed string is to have every single token be an English word.
For Example:
Input:
aman
Split Method:
a man
a m an
a m a n
am an
am a n
ama n
Desired Output:
a man
I currently have this code which does everything up until the desired output part:
import java.util.Scanner;
import java.io.*;
public class Words {
public static String[] dic = new String[80368];
public static void split(String head, String in) {
// head + " " + in is a segmentation
String segment = head + " " + in;
// count number of dictionary words
int count = 0;
Scanner phraseScan = new Scanner(segment);
while (phraseScan.hasNext()) {
String word = phraseScan.next();
for (int i=0; i<dic.length; i++) {
if (word.equalsIgnoreCase(dic[i])) count++;
}
}
System.out.println(segment + "\t" + count + " English words");
// recursive calls
for (int i=1; i<in.length(); i++) {
split(head+" "+in.substring(0,i), in.substring(i,in.length()));
}
}
public static void main (String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next();
System.out.println();
Scanner filescan = new Scanner(new File("src:\\dictionary.txt"));
int wc = 0;
while (filescan.hasNext()) {
dic[wc] = filescan.nextLine();
wc++;
}
System.out.println(wc + " words stored");
split("", input);
}
}
I know there are better ways to store the dictionary (such as a binary search tree or a hash table), but I don't know how to implement those anyway.
I am stuck on how to implement a method that would check the split string to see if every segment was a word in the dictionary.
Any help would be great,
Thank you

Splitting the input string every possible way is not going to finish in a reasonable amount of time if you want to support 20 or more characters. Here's a more efficient approach, comments inline:
public static void main(String[] args) throws IOException {
// load the dictionary into a set for fast lookups
Set<String> dictionary = new HashSet<String>();
Scanner filescan = new Scanner(new File("dictionary.txt"));
while (filescan.hasNext()) {
dictionary.add(filescan.nextLine().toLowerCase());
}
// scan for input
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next().toLowerCase();
System.out.println();
// place to store list of results, each result is a list of strings
List<List<String>> results = new ArrayList<>();
long time = System.currentTimeMillis();
// start the search, pass empty stack to represent words found so far
search(input, dictionary, new Stack<String>(), results);
time = System.currentTimeMillis() - time;
// list the results found
for (List<String> result : results) {
for (String word : result) {
System.out.print(word + " ");
}
System.out.println("(" + result.size() + " words)");
}
System.out.println();
System.out.println("Took " + time + "ms");
}
public static void search(String input, Set<String> dictionary,
Stack<String> words, List<List<String>> results) {
for (int i = 0; i < input.length(); i++) {
// take the first i characters of the input and see if it is a word
String substring = input.substring(0, i + 1);
if (dictionary.contains(substring)) {
// the beginning of the input matches a word, store on stack
words.push(substring);
if (i == input.length() - 1) {
// there's no input left, copy the words stack to results
results.add(new ArrayList<String>(words));
} else {
// there's more input left, search the remaining part
search(input.substring(i + 1), dictionary, words, results);
}
// pop the matched word back off so we can move onto the next i
words.pop();
}
}
}
Example output:
Enter a string: aman
a man (2 words)
am an (2 words)
Took 0ms
Here's a much longer input:
Enter a string: thequickbrownfoxjumpedoverthelazydog
the quick brown fox jump ed over the lazy dog (10 words)
the quick brown fox jump ed overt he lazy dog (10 words)
the quick brown fox jumped over the lazy dog (9 words)
the quick brown fox jumped overt he lazy dog (9 words)
Took 1ms

If my answer seems silly, it's because you're really close and I'm not sure where you're stuck.
The simplest way given your code above would be to simply add a counter for the number of words and compare that to the number of matched words
int count = 0; int total = 0;
Scanner phraseScan = new Scanner(segment);
while (phraseScan.hasNext()) {
total++
String word = phraseScan.next();
for (int i=0; i<dic.length; i++) {
if (word.equalsIgnoreCase(dic[i])) count++;
}
}
if(total==count) System.out.println(segment);
Implementing this as a hash-table might be better (it's faster, for sure), and it'd be really easy.
HashSet<String> dict = new HashSet<String>()
dict.add("foo")// add your data
int count = 0; int total = 0;
Scanner phraseScan = new Scanner(segment);
while (phraseScan.hasNext()) {
total++
String word = phraseScan.next();
if(dict.contains(word)) count++;
}
There are other, better ways to do this. One is a trie (http://en.wikipedia.org/wiki/Trie) which is a bit slower for lookup but stores data more efficiently. If you have a large dictionary, you might not be able ot fit it in memory, so you could use a database or key-value store like a BDB (http://en.wikipedia.org/wiki/Berkeley_DB)

package LinkedList;
import java.util.LinkedHashSet;
public class dictionaryCheck {
private static LinkedHashSet<String> set;
private static int start = 0;
private static boolean flag;
public boolean checkDictionary(String str, int length) {
if (start >= length) {
return flag;
} else {
flag = false;
for (String word : set) {
int wordLen = word.length();
if (start + wordLen <= length) {
if (word.equals(str.substring(start, wordLen + start))) {
start = wordLen + start;
flag = true;
checkDictionary(str, length);
}
}
}
}
return flag;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
set = new LinkedHashSet<String>();
set.add("Jose");
set.add("Nithin");
set.add("Joy");
set.add("Justine");
set.add("Jomin");
set.add("Thomas");
String str = "JoyJustine";
int length = str.length();
boolean c;
dictionaryCheck obj = new dictionaryCheck();
c = obj.checkDictionary(str, length);
if (c) {
System.out
.println("String can be found out from those words in the Dictionary");
} else {
System.out.println("Not Possible");
}
}
}

Related

How do i ignore same words in a string (JAVA)

I want to find how many words there are in a string but ignore the similar words in it.
For example the main method should return 8 insetad of 9.
I want it to be a method which takes one parameter s of type String and returns an int value. And im only allowed to use the bacics,so no HashMaps, ArrayLists, only charAt, length, or substring and using loops and if statemens are allowed.
public static void main(String[] args) {
countUniqueWords("A long long time ago, I can still remember");
public static int countUniqueWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}
```
Don't force yourself to limited options, and learn the Streaming API. Your question is as simple as:
public static long countUniqueWords(String str) {
var str2 = str.replaceAll("[^a-zA-Z0-9 ]", "").replaceAll(" +", " ");
return Arrays.stream(str2.split(" "))
.distinct()
.count();
}
[Optional step] Get get rid of all non alphanumeric chars
Split the string per empty slot
Remove duplicates
Add them together
To ignore same words in a string, you can use a combination of the split and distinct methods from the Java Stream API.
// Define the input string
String input = "This is a test string with some repeating words";
// Split the string into an array of words
String[] words = input.split("\\s+");
// Use the distinct method to remove duplicate words from the array
String[] distinctWords = Arrays.stream(words).distinct().toArray(String[]::new);
// Print the distinct words
System.out.println(Arrays.toString(distinctWords));
Try this:
public static int countUniqueWords(String words) {
// Add all the words to a list
List<String> array = new ArrayList<>();
Scanner in = new Scanner(words);
while (in.hasNext()) {
String s = in.next();
array.add(s);
}
// Save per word the amount of duplicates
HashMap<String, Integer> listOfWords = new HashMap<>();
Iterator<String> itr = array.iterator();
while (itr.hasNext()) {
String next = itr.next();
String prev = listOfWords.getOrDefault(next, 0);
listOfWords.put(next, prev + 1);
}
// Grab the size of all known words
return listOfWords.size();
}
public static void main(String args[]) {
int count = countUniqueWords("A long long time ago, I can still remember");
System.out.println("The number of unique words: " + count);
}

How to output the largest number in keySet if there are several such numbers?

How to output the largest word if there are several such numbers? (should output the one, which occurs earlier). My code didn't work properly.
import java.io.*;
import java.util.*;
public class solved {
public static void main(String[] args) {
LinkedHashMap<Integer, String> hashMap = new LinkedHashMap<>();
Scanner scan = new Scanner(System.in);
String[] str = scan.nextLine().split(" ");
for (int i=1; i < str.length; i++) {
int n = str[i].length();
String s = str[i];
hashMap.put(n, s);
}
int maxKey = Collections.max(hashMap.keySet());
System.out.println(hashMap.get(maxKey));
}
}
You may use putIfAbsent to avoid ovewriting an existing value and keep the earliest values
for (int i=1; i < str.length; i++) {
int n = str[i].length();
String s = str[i];
hashMap.putIfAbsent(n, s);
}
⚠️ Starting i at 1 makes the first word unused be careful, array are 0-indexed so start at 0 to get on every word
Since you're using a HashMap, if you have an entry later with a duplicate key, the previous entry will be overwritten. One way to deal with this would be to have a Map<Integer, List<String>> but that's just too complicated. It's better to just do it like this:
int longestN = -1;
String longest;
for (String s : str) {
int n = s.length();
if (n > longestN) {
longestN = n;
longest = s;
}
}
System.out.println(longest);
Do you want to store all words? In your exaple "dog" will replace "cat", so you lose the first word. If you want to store all words, you cannot have an Integer as key in a HashMap, because it can only ever have a single key for each value.
If you want to retain all words for some later use, you can invert your map to Map<String, Integer> - and use words as keys and lengths as values. Or, you could skip using Collections altogether:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] str = scan.nextLine().split(" ");
int longestWordLength = -1;
for (String s : str) {
if (s.length() > longestWordLength)
longestWordLength = s.length();
}
for (String s : str) {
if (s.length() == longestWordLength)
System.out.printf("Longest word: %s is %s", s, s.length());
}
}
Or, with Java 8 streams for fun and learning:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] str = scan.nextLine().split(" ");
int longest = Arrays.stream(str)
.mapToInt(String::length).max().orElse(-1);
Predicate<String> isLongest = s -> s.length() == longest;
String firstLongest = Arrays.stream(str)
.filter(isLongest).findFirst().orElse("no words");
System.err.println(firstLongest + " " + longest);
}

How to count length of words in a File? Java

I am trying to write a code which would count the number of words of a certain length in a file.
For example:
How are you?
would print:
Proportion of 3-letter words: 100% (3 words)
I want to count words of length 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13+
Can you please guide me?
I am NOT trying to find the number of words. I am already able to do with this code:
public static int WordCount() throws FileNotFoundException
{
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
count++;
}
return count;
}
I want to find words of a certain length.
UPDATE
I have written the following code:
public static int WordLengthCount() throws FileNotFoundException
{
File file = new File("hello.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count5 = 0;
int hell = 0; //This is just for the else command to compile
while(keyboard.hasNext())
{
if ( keyboard.next().length() == 5 )
{
count5++;
keyboard.next();
return count5;
}
} return hell;
}
You can use the length() method to count the number of characters in a string (word). From there on, it's just a matter of saving it somewhere. E.g., in Map:
public static Map<Integer, Integer> lengthCounts() throws FileNotFoundException
Map<Integer, Integer> countMap = new HashMap<>();
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
Integer currCount = countMap.get(length);
if (currCount == null) {
countMap.put (length, 1);
else {
countMap.put (length, currCount + 1);
}
}
return countMap;
}
Now you could check the number of words with any particular length, or even print all of them.
EDIT:
If the only thing you need is the percentage of words of a certain length, all you need are two counters - one for the words of that length, and one for all the words:
public static double lengthPercentage(int requiredLength) throws FileNotFoundException
int allWords = 0;
int requiredWords = 0;
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
if (length == requiredLength) {
++requiredWords;
}
++allWords;
}
// implicit assumption: there's at least on word in the file
return ((double) requiredWords) / allWords;
}
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
// Use a hash map
// Check the string length and add it to the hash map by checking it already exists. If already exists then get the actual value from hashmap and increment it by one and save it again to the map.
count++;
}
So that your final output will be of map with one letter string count, two letter string count etc..
The other answers are great, but if you are trying to find words of a specific length in a file and you don't like the answers above, then you could also try REGEX. You can test each word and then do what you want with it. If you are looking for a count of words in a file of each length, I think the answer above is better, but if you're looking to detect a word of a specific length you could use .length() or the regex below. Using a strings .lenght() function in my opinion is better, but I'm just giving you an alternative answer and example.
I'll put a small example below.
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.matches(".{5}")){
5++;
}
}
System.out.println(fives);
}
}
Or a better version:
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.length() == 5){
5++;
}
}
System.out.println(fives);
}
}
Edited Below: To demonstrate how it can be used in a file based loop
// other code needed
while(in.hasNext())
{
String s = in.next();
if(s.length() == 5)
fives++;
}
For example, I have text file named TextFile.txt at C:\ has content:
Ut porttitor libero sodales quam sagittis, id facilisis lectus semper.
and Java code:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
File file = new File("C:\\TextFile.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
if (dis.available() != 0) {
// Get the line.
String s = dis.readLine();
// Put words to array.
String[] sParts = s.split(" ");
// Initialize word longest length.
int longestLength = 1;
for (String strx : sParts) { // Go through each sPart, the next one is called strx
// If the document has word longer than.
if (longestLength < strx.length())
// Set new value for longest length.
longestLength = strx.length();
}
// Because array index from "0".
int[] counts = new int[longestLength + 1];
for (String str : sParts) {
// Add one to the number of words that length has
counts[str.length()] += 1;
}
// We use this type of loop since we need the length.
for (int i = 1; i < counts.length; i++) {
System.out.println(i + " letter words: " + counts[i]);
}
}
}
}
// Result:
// 1 letter words: 0
// 2 letter words: 2
// 3 letter words: 0
// 4 letter words: 1
// 5 letter words: 0
// 6 letter words: 2
// 7 letter words: 2
// 8 letter words: 0
// 9 letter words: 3

Reversing a string array in java

I need to make a program that takes a user entered sentence and reverses it with proper formatting and punctuation.
Ex:The quick brown fox jumps over the lazy dog.
RESULT: "Dog lazy the over jumps fox brown quick the."
I have seen solutions to this and I can get a correct answer by asking the user for 1 word at a time. However we are specifically asked to ONLY ask the user for the sentence, and then the program does the rest. So the program has to determine how large the array is, and assign each word in the string to a value in the array (i guess?).
So far this is what I have, however I think that I need to use a stringBuffer but I don't know how to implement this.
public class ReverseSentence {
public static void main(String[] args) {
String[] sentence = new String[]{IO.readString()};
for(int counter = 0; counter < sentence.length; counter++){
System.out.println("Enter Sentence"+(counter+1));
sentence[counter] = IO.readString();
}
System.out.println("The Reversed Sentence is:");
for(int counter = sentence.length - 1; counter >= 0; counter--){
System.out.print(sentence[counter]);
}
}
}
This is not for a homework assignment, just some practice problems for an upcoming exam, so a full solution would be fine, but if possible, with comment lines so I can see how you did it.
You have two distinct problems:
reversing the sentence
capitalising the sentence
Lets do the first part fist:
public static String reverseSentence(final String sentence) {
final Pattern pattern = Pattern.compile("[^A-Za-z']+");
final List<String> words = pattern.splitAsStream(sentence)
.map(String::toLowerCase)
.collect(toList());
final StringBuilder reversed = new StringBuilder();
final ListIterator<String> i = words.listIterator(words.size());
reversed.append(i.previous());
while (i.hasPrevious()) {
reversed
.append(" ")
.append(i.previous());
}
reversed.append(".");
return reversed.toString();
}
Double-check the code:
public static void main(String[] args) throws Exception {
System.out.println(reverseSentence("The quick brown fox jumps over the lazy dog"));
}
dog lazy the over jumps fox brown quick the.
Okay, now we need to capitalise the first word:
public static String capitalise(final String name) {
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
}
We just need to use this method on the first word:
public static String reverseSentence(final String sentence) {
final Pattern pattern = Pattern.compile("[^A-Za-z']+");
final List<String> words = pattern.splitAsStream(sentence)
.map(String::toLowerCase)
.collect(toList());
final StringBuilder reversed = new StringBuilder();
final ListIterator<String> i = words.listIterator(words.size());
reversed.append(capitalise(i.previous()));
while (i.hasPrevious()) {
reversed
.append(" ")
.append(i.previous());
}
reversed.append(".");
return reversed.toString();
}
Check it again:
Dog lazy the over jumps fox brown quick the.
You can try like this:
public static String reverseString(String input) {
//from input to this method
// split input with space and store words
// in a collection if input is not empty
Deque<String> words = new ArrayDeque<>();
for (String word: input.split(" ")) {
if (!word.isEmpty()) {
words.addFirst(word);
}
}
//now build output in reverse order of
// addition to collection if input is not empty
StringBuilder result = new StringBuilder();
while (!words.isEmpty()) {
result.append(words.removeFirst());
if (!words.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
Use Apache Commons StringUtils.
https://commons.apache.org/proper/commons-lang/
String result = StringUtils.capitalize(StringUtils.reverse(StringUtils.uncapitalize(basicString.substring(0,basicString.length()-1)))) + ".";
Try this. This code will give output of all case of format using full stop (.). And read the comment carefully.
Scanner inp = new Scanner(System.in);
String s1 = inp.nextLine();
String s2[] = s1.split(" ");
boolean full_stop = false;
// Printing first character of last string in upper case
System.out.print(Character.toUpperCase(s2[s2.length - 1].charAt(0)));
// Printing rest of the character of last string
if (s2[s2.length - 1].contains(".")) {// checking that (.) is exists then print without (.)
System.out.print(s2[s2.length - 1].substring(1,s2[s2.length - 1].length() - 1) + " ");
full_stop = true;
} else {
System.out.print(s2[s2.length - 1].substring(1, s2[s2.length - 1].length()) + " ");
}
for (int i = s2.length - 2; i >= 0; i--) {
if (i > 0) {
System.out.print(s2[i] + " ");
} else {
System.out.print(Character.toLowerCase(s2[i].charAt(0)));//converting first string character to lower case
System.out.print(s2[i].substring(1,s2[i].length()));// last string must not have space after that
}
}
if (full_stop) {// printing (.) if exists
System.out.println(".");
}

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[?] );
}
}
}
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.
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.
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;
}
}
Here's a solution using a map of WordInfo objects that records locations of the words within the text and uses that as a count. The LinkedHashMap preserves the order of keys from when they are first entered so simply iterating through the keys gives you the "cast in order of appearance"
You can make this case insensitive while preserving the case of the first appearance by storing all keys as lower case but storing the original case in the WordInfo object. Or just convert all words to lower case and leave it at that.
You may also want to think about removing all , / . / " etc from the first text before splitting, but you'll never get that perfect anyway.
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());
}
}
}
And the WordInfo class:
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;
}
}
Thanks for trying to help me. -This is what I ended up doing:
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));
}
}
}

Categories

Resources