gpt4 book ai didi

java - 需要有关 Java 字符串的帮助

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

我需要帮助获取长度 >= 用户给出的最小长度的字符串数量。例如:字符串输入“this is a game”minlength = 2。该句子中 3 个单词的长度 >= minLength,因此输出应为 3。因为 3 个单词 >= minLength

我遇到输出问题。我输入一个字符串,将其分成单独的单词,然后将它们发送到计算输出的方法。上面的示例所需的是 3,但我得到的是 1,1,1。

public class WordCount {

/**
* @param args
*/

public static String input;
public static int minLength;

public static void Input() {

System.out.println("Enter String: ");
input = IO.readString();

System.out.println("Enter minimum word length: ");
minLength = IO.readInt();

}

public static void Calc() {

Input();

String[] words = input.split(" ");

for (String word : words) {

LetterCount(word);
}

}

public static int LetterCount(String s) {


int countWords = 0;


if (s.length() >= minLength) {

countWords += 1;

IO.outputIntAnswer(countWords);

}



return countWords;

}

public static void main(String[] args) {
// TODO Auto-generated method stub

Calc();

}

}

最佳答案

你已经很接近了!

您为每个单词调用 LetterCount,并在 LetterCount 开始时将 countWords 设置为 0。因此,您的计数器每次都会重置!

不要将 countWords 作为 LetterCount 的局部变量,而是类中的私有(private)变量。

地点

private static int countWords = 0;

位于文件顶部。

删除

int countWords = 0;

来自 LetterCount。

关于java - 需要有关 Java 字符串的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365177/

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