无限循环计数令牌Java

时间:2015-09-11 03:06:56

标签: java loops while-loop

我正在尝试编写一个小程序来计算字符串words中的单词数并将其打印到控制台。但每次我运行它,它都是无限循环。我错过了什么?

public static void main (String[] args){

  String words = "This is the sentence I want to use";

  Scanner s = new Scanner(words);
  int count = 0;

  while(s.hasNext()){
    count ++;
  }

  System.out.println(count);
}

1 个答案:

答案 0 :(得分:2)

您实际上并未解析任何内容,您需要通过next()函数从扫描程序中获取令牌:

while (s.hasNext())
{
  ++count;
  s.next();
}