【发布时间】:2018-04-15 17:10:46
【问题描述】:
java 的任务是编写一个接受字符串对象作为参数并返回它包含的单词数的方法。在要求用户输入字符串并将其传递给方法的程序中演示该方法。字数应显示在屏幕上。我知道它很接近,但可能有一些错误。
public class WordCounter
{
//Asks and gets the users input here
private static string getInput(Scanner in)
{
String input;
//Imported scanner here
Scanner in = new Scanner(System.in);
//Ask the user to enter string here
System.out.println("Enter a string here: ");
input = in.nextLine();
//Create an if/else statment to find out if the user entered input
if(input.length() > 0)
{
getInput(input); //Get word count
}
else
{
System.out.println("Error -- You must enter a string!");
System.out.println("Enter a string here: ");
input = in.nextLine();
}
return input;
} //Close public static string getInput here
//Calculates the number of words the user inputs
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
} //Close public static int getWordCount here
//Prints out the number of words from the users input in string above
public static void main(String[] args)
{
//Print out the number of words within the users string here
System.out.println("The number of words in the string are: " + counter);
} //Close public static void main string args here
【问题讨论】:
-
如果您遇到具体问题,请提出。
标签: java word-count