gpt4 book ai didi

java - Java 无限 while 循环计数标记

转载 作者:行者123 更新时间:2023-12-02 04:23:14 26 4
gpt4 key购买 nike

我正在尝试编写一个小程序来计算字符串 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);
}

最佳答案

您实际上并没有解析任何内容,您需要通过 next() 函数从扫描仪获取 token :

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

关于java - Java 无限 while 循环计数标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32514848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com