日期:2014-05-20  浏览次数:20773 次

怎样一个单词一个单词的输出?
import   java.util.*;
class   Example
{
public   static   void   main(String   args[])
{
String   s=new   String( "we,go,to,shchool,yeah ");
StringTokenizer   token=new   StringTokenizer(s, ", ");
int   n=token.countTokens();
String   word=token.nextToken();
System.out.printf( "%s,%d ",word,n);

}
}
大虾帮我改下

------解决方案--------------------
StringTokenizer 是出于兼容性的原因而被保留的遗留类(虽然在新代码中并不鼓励使用它)。建议所有寻求此功能的人使用 String 的 split 方法或 java.util.regex 包。

下面的示例阐明了如何使用 String.split 方法将字符串分解为基本标记:

String[] result = "this is a test ".split( "\\s ");
for (int x=0; x <result.length; x++)
System.out.println(result[x]);

对于你的代码,最佳方法是
public static void main(String args[])
{
String s=new String( "we,go,to,shchool,yeah ");

String words[] = s.split( ", ");

for(String word : words)
{
System.out.println(word);
}
}
------解决方案--------------------
按你要求可以把你的程序修改如下:
import java.util.*;
class Example
{
public static void main(String args[])
{
String s=new String( "we,go,to,shchool,yeah ");
StringTokenizer token=new StringTokenizer(s, ", ");
int n=token.countTokens();
while(token.hasMoreTokens())
{
String word=token.nextToken();
System.out.println(word);
}
System.out.println( "共有单词: "+n+ "个 ");

}
}