Rahul
Posts: 52
Nickname: wildhorse
Registered: Oct, 2002
|
|
Re: help with a loop to read every 10th word
|
Posted: Nov 22, 2002 3:16 AM
|
|
Jason,
The problem with a StringTokenizer is that after traversing the entire string once, you will have to re-initialize it to traverse it again. That means that once you've read.. say the 50th token and now want to read the 3rd token, you cannot. Since you've already been thro' the 3rd to reach the 50th you cannot go back to it again...until of course you initialize the tokenizer again.
You may try taking the tokens and filling them up in a vector and then traversing it to show the output the way you want.
But if you really need to use the StringTokenizer then here's what you can do:
import java.util.Vector; import java.util.StringTokenizer;
class tryVect { public static void main(String[] args) { // This is string you might construct. i have added numbers behind for easy verification. Haven't had time for empty tokens. you can try that i'm sure :)
String mainStr = "The1,request2,goes3,to4,the5,controller6,section7,where8,it9,is10,handled11,by 12,a13,Request14,Intercepting15,Filter.16,This17,servlet18,filter19,receives20,t he21,request22,and23,does24,the25,necessary26,security27,checks.28,It29,then30,p asses31,the32,request33,to34,the35,Front36,Controller37,servlet.38,The39,Front40 ,Controller's41,job42,is43,to44,pull45,out46,data47,from48,the49,request50,form5 1,and52,create53,an54,event55,object56,with57,that58,data.59";
StringTokenizer str = new StringTokenizer(mainStr,","); int first=1,i = 1; Object o; int count = str.countTokens(); // This is the main loop
while (str.hasMoreTokens() && i<=10) // will run only 10 times. { str = new StringTokenizer(mainStr, ","); int temp = 1; /* As the StringTokenizer begins from 1 every time, this help the loop to omit token 1 when it should begin with 2 and so..on. Try without this loop also. */ while (i > 1) { o = str.nextElement(); if (++temp == i) { break; } } // here is where you traverse thro' the entire thing for 10th position tokens.
for (int j = i;j < count ;j++) { o = str.nextElement(); if (((j-first) == 10) || (j == first)) { System.out.print(o.toString()+" "); first = j; } }
System.out.println(""); // increase counters i++; first = i; } } }
|
|