總之,這段代碼是一個空格分隔標記器,它將字符串分成多達三塊。
因此,在這個特殊的例子,S1的值,S2和S3將是:
s1 = "You";
s2 = "are";
s3 = "cool";
查看存儲在其中的價值,只是做:現在
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
,如爲爲什麼?
參見此:
String s1, s2, s3="";//these are the strings that will hold the sub tokens
StringTokenizer line = new StringTokenizer("You are cool");//this initializes an object of the StringTokenizer class with a string value of "You are cool"
s1 = line.nextToken();//this reads up until the first whitespace character (which will be skipped)
s2 = line.nextToken();//this will read from the last position of the iterator
//this will continue reading tokens (delimited by whitespace) from the initialized
//StringTokenizer, (now at the position after "are"):
while (line.hasMoreTokens())
s3 +=line.nextToken();//and those tokens are **appended** to s3! Note appended! Not stored in or overwritten to!
因此,聲稱*該程序標記化的字符串最多三次(由空格)。
但是,你應該警告:因爲,在StringTokenizer的初始化此情況下:
"You are cool, bro"
(注意額外的空格和字符空格以下)
你」得到這個:
s1 = "You";
s2 = "are";
s3 = "cool,bro";//note the lack of whitespace!
最後一部分來自的事實是,在while循環:
while (line.hasMoreTokens())
s3 +=line.nextToken();//a nextToken() call skips over whitespace by default
因此,S3從line
追加下一個的道理,無論多少有。
該代碼沒有「輸出」(如在命令行輸出中,因爲沒有'System.out.println')。不知道這是否有幫助。有關如何打印,請參閱[本](http://ideone.com/JW4gWW)。 – Dukeling