gpt4 book ai didi

java - 编写代码以使用方法查找字符串中的单词数

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

我一直在寻找,但在任何地方都找不到如何使用 3 种方法编写字数统计。这是到目前为止代码的样子。我不知道如何使用这些方法。我可以不使用不同的方法而只使用一种方法来做到这一点。请帮忙!!!

    public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}

// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body

// NOTE: Do not declare a Scanner in the body of this method.
}


// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}

}

编辑:我已将代码更改为

private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}


private static int getWordCount(String s) {
return s.split(" ");
}

但我无法将字符串转换为整数。

最佳答案

您已阅读该方法的名称,并查看注释来决定该方法内应实现什么以及应返回的值。

getInputString 方法签名应该是:

private static String getInputString(Scanner s) {

String inputString = "";

// read the input string from system in
// ....

return inputString;

}

getWordCount 方法签名应为:

private static int getWordCount(String input) {

int wordCount = 0;

// count the number of words in the input String
// ...

return wordCount;
}

main 方法应如下所示:

public static void main(String[] args) {

// instantiate the Scanner variable

// call the getInputString method to ... you guessed it ... get the input string

// call the getWordCount method to get the word count

// Display the word count
}

关于java - 编写代码以使用方法查找字符串中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238148/

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