java - find the most common name in textfile -


i have homework assignement, stuck on.

i have find commond name in text file, each line. if there tie, use first name had many occurrences. if names unique, print first name on line.

the files input: benson eric eric kim kim kim jenny nancy nancy paul paul ethan jamie jamie alyssa alyssa helene helene jessica jessica.

the result: common: kim common: jamie

this code: paul , jessica.

i need hold result how many times names have been repeated, cannot see miss.

this code have been trying.

public static void mostcommonnames(scanner input)  {       int count = 0;      int countname = 0;        while(input.hasnextline())      {          string commonname = "";         string commonname1 = "";        string line = input.nextline();           scanner token = new scanner(line);         while(token.hasnext())        {             string name = "";              int max = 0;               int longcurrent = 0;              int = 0;                       string tokenname = token.next();              if(tokenname.equals("benson") || tokenname.equals("eric") ||                tokenname.equals("kim") || tokenname.equals("jenny") ||                tokenname.equals("nancy") || tokenname.equals("paul") ||               tokenname.equals("ethan") || tokenname.equals("jamie") ||                tokenname.equals("alyssa") || tokenname.equals("helene") ||               tokenname.equals("jessica"))            {                               count++;              }            if(commonname.equals(tokenname))            {                countname++;                if(i < countname)               {                   longcurrent = i;               }             }             if(max < count)            {               commonname = tokenname;             }          }                  system.out.print(commonname + " ");                              }          system.out.print(countname + " ");               }  } 

hope me guidance, not result.

you can maintain map<string, int> namecount = new hashmap<string, int>(); assign key 0 all. after increment key value in map each name repeated each time.

while(token.hasnext()) {     string name = token.next();     int count = namecount.containskey(name) ? namecount.get(name) : 0;     namecount.put(name, count + 1); } 

after print name highest key value or whatever way want. if don't want use hashmap can maintain integer array in each element holds count each distinct name.

int namecount[]=new int[total_number_of_distinct_names];//array should initialized 0 while(token.hasnext()) {     string name = token.next();     namecount[index_associated_to_name]++; } 

be careful increment index value associated specific name, rest same.i think sufficient...


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -