简体   繁体   中英

Java Beginner - Counting number of words in sentence

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 only receive a count of 1 word. If you could tell me how to fix what I wrote rather than give me a completely different idea that would be great:

import java.util.Scanner;

public class P5_7 
{
    public static int countWords(String str)
    {
        int count = 1;
        for (int i=0;i<=str.length()-1;i++)
        {
            if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
            {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = in.next();
        System.out.print("Your sentence has " + countWords(sentence) + " words.");
    }
}

An easy way to solve this problem:

return str.split(" ").length;

Or to be more careful, this is how you'd take into account more than one whitespace:

return str.split("\\s+").length;

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

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

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

It will return number of words in your sentence.

Should you not have int count = 0; instead of int count = 1; , in case of blank sentences. If you're getting Java errors please could you add them to your question.

i<=str.length()-1应该是i<str.length()-1或者你将在str.charAt(i+1)得到一个IndexOutOfBoundsException(可用的值是str.charAt(0)str.charAt(str.length()-1) )。

Please check for boundary conditions at str.charAt(i+1) . It can result in a StringIndexOutOfBoundsException when the string is terminated by a space.

  1. Account for cases where the string starts with a ' '
  2. The String could be blank.
  3. The definition of a 'word' could differ. For example - '1 2'. Are 1,2 words ?

I know you do not want an alternate method but string.split(" ").length() is an easier way to start.

Actually, if you enter a sentence like:

"Hello World"

your code String sentence = in.next(); will only get the first word in the sentence ie, Hello . So, you need to use in.nextLine() in place of in.next() to get the whole sentence ie, Hello World .

This is how i have done it :

It works fine too

    import java.util.Scanner;


    public class countwords {

        public static void main(String args[]){
            Scanner in=new Scanner(System.in);
            System.out.println("Enter your sentence:[Try to ignore space at end]");
            String s=in.nextLine();
            System.out.println("Size of the string is "+s.length());
            int res=count(s);
            System.out.println("No of words in the given String --->>"+"  "+s+" "+"is"+" :"+res);
        }


        private static int count(String s) {
            // TODO Auto-generated method stub
            int count=0;
            if(s.charAt(0)!=' '){
                count++;
            }
            for(int i=0;i<s.length();i++){
                if((s.charAt(i)==' ')){
                    count++;
                }
            }
            return count;
        }


}

OUTPUT: this is my world bonaza

Size of the string is 23

No of words in the given String --->> this is my world bonazais :5

There are some bugs try to correct them and repost

A more simple way that i found was :

Just use this :

    // Read a string
String st=s.nextLine();

// Split string with space
String words[]=st.trim().split(" ");
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.");
}

}

Tested method - handles all inputs

public static void countwords() {
    String s = "  t    ";
    int count = 0;
    int length = s.length()-1;
    char prev = ' ';

    for(int i=length; i>=0; i--) {
        char c = s.charAt(i);
        if(c != prev && prev == ' ') {
            count++;
        }
        prev = c;
    }
    System.out.println(count);
}

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);
    }
}

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

public class WordrCount {

public static void main(final String[] args) {
    System.out.println("Please Enter Your String: ");
    final Map<String, Integer> hm = new HashMap<String, Integer>();
    final Scanner sc = new Scanner(System.in);
    final String s1 = sc.nextLine();
    final String[] c1 = s1.split(" ");
    for (int i = 0; i < c1.length; i++) {
        if (!hm.containsKey(c1[i])) {
            hm.put(c1[i], (Integer)1);
        }// if
        else {
            hm.put(c1[i], hm.get(c1[i]) +(Integer) 1);

        }// else
    }// for

    System.out.println("The Total No Of Words: " + hm);

}// main

}// WordCount

I'd suggest to use BreakIterator . This is the best way to cover not standard languages like Japanese where there aren't spaces that separates words.

Example of word counting here .

Here is one more method just using split , trim , equals methods to improve code and performance.

This code will work with space as well.

public int countWords(String string){
    String strArr [] = string.split("\\s");
    int count = 0;
    for (String str: strArr) {
        if(!str.trim().equals("")){
            count++;
        }
    }
    return count;
}

Use this method to calculate the number of words in a String:-

    private int calculateWords(String s){

    int count=0;

    if(s.charAt(0)!=' ' || s.charAt(0)!=','){

        count++;

    }

    for(int i=1;i<s.length();i++){
            if((s.trim().charAt(i)==' ' && s.charAt(i+1)!=' ')  || (s.trim().charAt(i)==',' && s.charAt(i+1)!=',')){

                count++;
            }

    }

    return count;
}
class Words {
public static void main(String[] args) {

    String str="Hello World this is new";
    str=str.trim();
    int n=str.length();
    char a[]=new char[n];
    str.getChars(1,n,a,0);
    for (int i=0;i<str.length() ; i++){
        if(a[i]==' ') count++;
    }
    System.out.println("No. of words = "+(count+1));
}

}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM