Loop through JAVA StringTokenizer -


please need badly. thank you

i read text file hard disk contains follows....

void main() {      int = 5;     int b = 5;     int c ;      c = + b;     cout << c ;   } 

so, need that.. lets have array of...

string []keyword = {"void", "main()"}; string []datatype = {"int", "float"}; 

so want loop through each token , check whether example key word or datatype. used java netbeans , code follows

int k = 0; int l = 0;  stringtokenizer tokens;  while ((currentline = readfile.readline()) != null) {     tokens = new stringtokenizer(currentline, " ", true);     (int = 0; tokens.hasmoretokens(); i++)     {         if (tokens.nexttoken().contains(keyword[k]))         {             jtextarea1.append(keyword[k] + "\n");             k++;         }          else if (tokens.nexttoken().contains(datatype[l]))         {             jtextarea2.append(datatype[l] + "\n");         }     }  }  

no, code won't work. while you're iterating on tokens never increment k , l remain 0 through out; implying you're checking first keyword , data type only.

recommendations

  • use simpler string.split() instead of stringtokenizer used when have more 1 delimiters , bit more advanced needs basic split. , since you're passing returndelims true (third parameter) you're receiving spaces tokens (which ins't want suppose).

  • use hashset<string> store keywords/datatypes instead of array or arraylist. give better performance compared iterating array or using arraylist.contains().

  • sample implementation

    hashset<string> keywords = new hashset<string>(         arrays.aslist(new string[] {"void", "main()"})); hashset<string> datatypes = new hashset<string>(         arrays.aslist(new string[] {"int", "float"}));  string newline = system.getproperty("line.separator"); while ((currentline = readfile.readline()) != null) {     string[] tokens= currentline.split(" ");     (string token : tokens) {         if (keywords.contains(token)) {             jtextarea1.append(token + newline);         } else if (datatypes.contains(token)) {             jtextarea2.append(token + newline);         }     }  } 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -