2013-04-14 132 views
0

執行以下代碼後,s1,s2和s3的值是什麼?代碼段說明

String s1, s2, s3=""; 
StringTokenizer line = new StringTokenizer("You are cool"); 
s1 = line.nextToken(); 
s2 = line.nextToken(); 
while (line.hasMoreTokens()) 
    s3 +=line.nextToken(); 

請注意,這是一個學習指南問題,我無法找到。如果任何人都可以徹底解釋,以便我可以在考試中提出這類問題,我將不勝感激。

+3

該代碼沒有「輸出」(如在命令行輸出中,因爲沒有'System.out.println')。不知道這是否有幫助。有關如何打印,請參閱[本](http://ideone.com/JW4gWW)。 – Dukeling

回答

0

字符串s1s2s3被實例化爲空不爲空

變量line基本上是一個準備被標記的新字符串("You are cool")。

每次你做nextToken()它會採取一個詞或令牌,並將其存儲在varible

所以這段代碼將存儲的前兩個單詞。

s1 = line.nextToken(); 
s2 = line.nextToken(); 

此代碼將會看到,如果他們是多個單詞或令牌,其中它們是:(1左)。然後,它會採取最後一個記號,它明智分配給s3

while (line.hasMoreTokens()) { 
    s3 +=line.nextToken(); 
} 

輸出,程序沒有心理上輸出任何東西到控制檯,然而這樣做在內存中。這就是它在內存中的樣子,如果你要輸出每個變量System.out.println()

s1 = "You"

s2 = "are"

s3 = "cool"

+0

因此,如果StringTokenizer的參數是(「要理解6中的概念」),則s1將是前兩個單詞(令牌),s2是後兩個單詞(令牌),s3是最後三個單詞(令牌) ? –

+1

沒有's1'是第一個單詞,'s2'是下一個單詞。和's3'因爲它在while循環中並且有'+ ='操作符,這意味着它將會添加到它並等於它將成爲句子的其餘部分。 –

0

正如@Dukeling提到的,因爲你不打印出任何你可能SRE無輸出。

另外,請德安這個答案一看: Why is StringTokenizer deprecated?

從Javadoc文檔的StringTokenizer: 的StringTokenizer是保留兼容性的原因,雖然它的使用是在新代碼氣餒的遺留類。建議任何尋求此功能的人使用String或java.util.regex包的拆分方法。

1

總之,這段代碼是一個空格分隔標記器,它將字符串分成多達三塊。

因此,在這個特殊的例子,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追加下一個的道理,無論多少有。