无法使用 StringTokenizer 获取所有令牌元素

我正在尝试使用 StringTokenizer 将字符串拆分为 "," 但无法获取整个值,令牌计数显示 3 但仅打印两个元素,如果我尝试使用其他两个输入“Ravi,Tuti,786”,则在下面添加了我的代码 " - 相同的输出 "Ravi,Tuti,786,pincode" 得到三个令牌而不是最后一个


public class Tokenizer{

public static void main(String[] args){

String str = "Ravi,Tuti,786";//survival of fittest,journey to get job,update skill,try,get job";

        StringTokenizer stk = new StringTokenizer(str,",");

        System.out.println(stk.countTokens());

        for(int i=0;i<=stk.countTokens();i++){

        System.out.println(stk.nextToken());}

}

}

输出是


3

Ravi

Tuti


呼啦一阵风
浏览 178回答 3
3回答

慕斯709654

使用hasMoreTokens()有nextToken:public class Tokenizer{&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; String str = "Ravi,Tuti,786";//survival of fittest,journey to get job,update skill,try,get job";&nbsp; &nbsp; &nbsp;StringTokenizer stk = new StringTokenizer(str,",");&nbsp; &nbsp; &nbsp;System.out.println(stk.countTokens());&nbsp; &nbsp; &nbsp;while (stk.hasMoreTokens()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(stk.nextToken());&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}}您的方法的问题在于您正在循环中运行countTokens,在调用for后nextToken会发生变化。如果要使用for循环,则需要将令牌计数保存到变量中:int numTokens = stk.countTokens();for (int i = 0; i < numTokens; i++) {&nbsp; System.out.println(stk.nextToken());}

呼如林

你应该使用hasTokens()方法。for( ; stk.hasMoreTokens() ; ) {&nbsp; &nbsp; System.out.println(stk.nextToken());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java