Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

Java Word Counter -- Write method that accepts string object as argument and returns word count

The assignment for java is to write a method that accepts string objects as an argument and returns the number of words it contains. Demonstrate the method in a program that asks the user to input a string and passes it to the method. The number of words should be displayed in the screen.. I know its close but there are probably some errors.

public class WordCounter
{

    public static void main(String[] args)
    {

        //Imported scanner here
        Scanner in = new Scanner(System.in);

        //
        //Asks and gets the users input here
        //
        private static string getInput(Scanner in)
        {
            String input;

            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);
            }
            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)
        {
            int wordcount = 0;  //Initializes word counter to 0 at start of program

            for(int i = 0;  i  <= input.length() -1; i++)
                {
                    if(input.charAt(i) == ' ')
                    {
                        wordcount++;
                    }
                }

                return wordcount;

        }   //Close public static int getWordCount here


        //Print out the number of words within the users string here
        System.out.println("The number of words in the string are: " + wordcount);

    }   //Close public static void main string args here

}   //Close public class word counter here
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this smple method to find wordCount,

    public int getWordCount(String value)
    {
        String[] result = value.split(" ");
        return result.length;
    }

you wrote all the methods in your main method it wont compile. Place it out side and then try.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...