Java Beginner - Counting number of words in sentence

后端 未结 17 1670
忘了有多久
忘了有多久 2021-01-01 05:29

I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn\'t work. No matter what I write, I on

相关标签:
17条回答
  • 2021-01-01 06:08

    The simple logic is count the spaces only if there aren't any white spaces before. Try this:

    public class WordCount 
    {
        public static void main(String[] args) 
        {
            int word=1;
            Scanner s = new Scanner(System.in);
            System.out.println("Enter a string: ");
            String str=s.nextLine();
            for(int i=1;i<str.length();i++)
                {
                    if(str.charAt(i)==' ' && str.charAt(i-1)!=' ')
                    word++;
                }
           System.out.println("Total Number of words= "+word);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 06:09

    Try This Simple Code with split() and argument as spaces

    int length=str.split(" ").length;
    

    It will return number of words in your sentence.

    0 讨论(0)
  • 2021-01-01 06:14
    package test;
    public class CommonWords {
        public static void main(String[] args) {
            String words = "1 2 3 44 55                            966 5                                   88              ";
            int count = 0;
            String[] data = words.split(" ");
            for (String string : data) {
                if (!string.equals("")) {
                    count++;
                }
            }
            System.out.println(count);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 06:16

    You need to read entire line. Instead of in.next(); use in.nextLine().

    0 讨论(0)
  • 2021-01-01 06:19
    This program works fine, 
    

    step1:input the string

    step2:split the string into single word store in a arrays

    step3 :return the length of the arrays

    public class P5_7 
    {
    public static int countWords(String str)
    {
       String words[]=str.split(" ");
       int count=words.length;
        return count;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence =in.nextLine();
        System.out.print("Your sentence has " + countWords(sentence) + " words.");
    }
    

    }

    0 讨论(0)
提交回复
热议问题