java - List names and number of occurrences -
so task read file following names:
alice bob james richard bob alice alice alice james richard bob richard bob stephan michael henry
and print out each name value of occurrence e.g "alice - <4>".
got working, basically. problem have last name (stephan - <1>) missing in output , can't work properly.. it's because used [i-1] said, i'm not getting right solution here.
well, here's code..
package assignment4; import java.io.filenotfoundexception; import java.io.filereader; import java.io.ioexception; import java.io.inputstreamreader; import java.io.bufferedreader; import java.util.arrays; public class reportuniquenames { public static void main(string[] args) { // todo auto-generated method stub system.out.println (" programm counts words, characters , lines!\n"); system.out.println ("please enter name of .txt file:"); bufferedreader input = new bufferedreader(new inputstreamreader (system.in)); bufferedreader read = null; string file = ""; string text = ""; string line = ""; boolean unique = true; int namecounter = 1; try { file = input.readline(); read = new bufferedreader (new filereader(file)); while ((line = read.readline()) != null) { text += line.trim() + " "; } } catch (filenotfoundexception e) { system.out.println("file not found."); } catch (ioexception e) { system.out.println("an error has occured."); } string textarray[] = text.split(" "); arrays.sort(textarray); (int i=0; < textarray.length; i++) { if (i > 0 && textarray[i].equals(textarray[i-1])) { namecounter++; unique = false; } if (i > 0 && !textarray[i].equals(textarray[i-1]) && !unique) { system.out.println("<"+textarray[i-1]+"> - <"+namecounter+">"); namecounter = 1; unique = true; } else if (i > 0 && !textarray[i].equals(textarray[i-1]) && unique) { //namecounter = 1; system.out.println("<"+textarray[i-1]+"> - <"+namecounter+">"); } } } }
so that's it.. 1 of me out.
edit:
wow, many different approaches.
first of of help.
i'll through suggested solutions , maybe restart bottom ;).
give heads when i'm done.
you use map
(that emulates "multiset") purpose of counting words:
string textarray[] = text.split(" "); // treemap gives sorting alphabetical order "for free" map<string, integer> wordcounts = new treemap<>(); (int = 0; < textarray.length; i++) { integer count = wordcounts.get(textarray[i]); wordcounts.put(textarray[i], count != null ? count + 1 : 1); } (map.entry<string, integer> e : wordcounts.entryset()) { system.out.println("<" + e.getkey() + "> - <" + e.getvalue() + ">"); }
Comments
Post a Comment