【问题标题】:Java Word Counter -- Write method that accepts string object as argument and returns word countJava Word Counter -- 接受字符串对象作为参数并返回字数的写入方法
【发布时间】:2014-04-04 02:47:05
【问题描述】:

java 的任务是编写一个接受字符串对象作为参数并返回它包含的单词数的方法。在要求用户输入字符串并将其传递给方法的程序中演示该方法。字数应该显示在屏幕上。我知道它接近但可能有一些错误。

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

【问题讨论】:

标签: java string


【解决方案1】:

试试这个简单的方法来找到字数,

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

您在 main 方法中编写了所有方法,它不会编译。把它放在外面然后试试。

【讨论】:

    【解决方案2】:

    更正:

    1. 如果有任何字符,您需要调用 getWordCount 输入字符串

      if(input.length() > 0)
      {
          getInput(input);    // getWordCount(input);
      }
      
    2. 如果你只是想计算字符串中的单词数,这样做

      int counter = 0;
      for(int i = 0;  i  <= input.length() -1; i++) {
          counter++;
      }
      
    3. 如果您想避免计算放置的空格,则条件并继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2016-10-06
      相关资源
      最近更新 更多