java - Trying to figure out why the split method is not printg out right -


the words printed out after split command not printing out in ascending order. not think have placed in right spot of code, unsure place it. prints out whole text passage word word without punctuation marks desired, wont print in ascending (alphabetical) order. great.

public static void main(string[] args) throws          filenotfoundexception, ioexception  {     scanner ci = new scanner(system.in);     system.out.print("please enter text file open: ");     string filename = ci.next();     system.out.println("");      file file = new file(filename);     bufferedreader br = new bufferedreader(new filereader(file));      stringbuilder sb = new stringbuilder();     string str;      while((str = br.readline())!= null)     {         string sp[] = str.split("[\\s\\.,;:\\?!]+");         (string sr : sp )         {             system.out.println(sr);         }                      sb.append(str);         sb.append(" ");         // system.out.println(str);                 }      arraylist<string> text = new arraylist<>();     stringtokenizer st = new stringtokenizer(sb.tostring().tolowercase());     while(st.hasmoretokens())      {         string s = st.nexttoken();         text.add(s);     }      system.out.println("\n" + "words printed out in ascending "                             + "(alphabetical) order: " + "\n");      list<string> arraylist = new arraylist<>(text);     collections.sort(arraylist);     (object ob : arraylist)     {         system.out.println("\t" + ob.tostring());     } } 

you're printing words twice, once after you've splitted text on punctuation, again after you've glued together, splitted again , sorted it.

however, in line-reading while you're splitting each line, you're ignoring result of split (besides printing it) , continue add original line sb.

you want turn sb arraylist, add each word (sr sp in for(sr : sp) loop) sb , sort that.

you can remove whole part stringtokenizer , sort arraylist immediately. this:

arraylist<string> sb = new arraylist<string>(); string str;  while((str = br.readline())!= null) {     string sp[] = str.split("[^\\w]+");     (string sr : sp )     {         sb.add(sr);         // system.out.println(sr);     }           } sb = collections.sort(sb); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -