It uses a solution using the WordInfo object map, which records the locations of words in the text and uses this as a counter. LinkedHashMap preserves the order of the keys from the moment they are first entered, so a simple repetition with the keys gives you a "tidy appearance"
You can make this case insensitive by preserving the first occurrence case, keeping all keys as lowercase, but keeping the original case in the WordInfo object. Or just put all the words in lower case and leave it on that. You might also consider deleting everyone , / . / " , etc. From the first text before splitting, but in any case you will never get this perfection.
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; } }
source share