gpt4 book ai didi

java - Java 中的字数统计

转载 作者:行者123 更新时间:2023-12-01 17:27:26 25 4
gpt4 key购买 nike

我正在为我的 CS 期末练习做一些练习,并且遇到了这个问题,我必须读取一个字符串,从用户那里获取最小长度,并返回至少包含那么多字母的单词数量。看起来我的代码没问题,但无法打印出答案。谁能帮帮我吗?

public class WordCount {



public static void main (String [] args) {
System.out.println("Enter a string: ");
String input = IO.readString();


System.out.println("Enter minimum word length");
int wordlength = IO.readInt();
int count = 0 ;
do {

for (int i = 0 ; i < input.length(); i ++) {

if (input.indexOf(i) == ' ') {

String check = input.substring(0, i);
if (check.length() >= wordlength) {

count++;
input = input.substring(i);
break;

}
}

}

} while (input.length() > 0);


System.out.print("Words longer than " + wordlength + " characters: " + count);

}

}

似乎 while 循环无限运行,但我不明白为什么!

最佳答案

我将简单地使用 split ,如下所示:

    System.out.println("Enter minimum word length");
int wordlength = IO.readInt();
int count = 0 ;
//get all words in string array by splitting the input around space
String[] words = input.split(" ");//assuming words are separated by space

//now iterate the words, check the length, if word is of desired length or more
//increase the word counter
for (int i = 0 ; i < words.length; i ++) {
if (words[i].length() >= wordlength) {
count++;
}
}

关于java - Java 中的字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13771087/

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