1

I'm trying to get a word count of a string entered by a user but I keep getting "0" back as a result. I can't figure out what to do.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner reader=new Scanner(System.in);
    ArrayList<String> A=new ArrayList<String>();

    System.out.print("Enter a sentence: ");
    String a=reader.next();

    int charCount=a.length();
    int space;
    int period;
    int wordCount=0;
    //word count\

    for (int i=0; i<1; i++){
        space=a.indexOf(" ");
        if (a.charAt(0)!=' '){
            if (space!=-1){
                A.add(i, a.substring(0, space-1));
                a=a.substring(a.indexOf(" ")+1, charCount-1);
            }
            if (space==-1&&a.charAt(charCount-1)=='.'){
                period=a.indexOf(".");
                A.add(i, a.substring(0, period));
            }
            charCount=a.length();
        }
        wordCount=A.size();
    }
    System.out.print("Word Count: "+A.size());  
}
3
  • reader.next() only gets a single word. Try reader.nextLine(). Commented Mar 2, 2017 at 2:39
  • 1
    And besides, can't you just use sentence.trim().split(" ").length? (I renamed a to sentence because it makes more sense) Commented Mar 2, 2017 at 2:40
  • Alternately, you can use reader.next() to repeatedly read words and count them and get rid of your indexOf(" "). Commented Mar 2, 2017 at 2:41

1 Answer 1

1

Why don't you try like this-

public static void main (String[] args) {
    Scanner reader=new Scanner(System.in);

    System.out.println("Enter a sentence: ");

    String str1 = reader.nextLine();

    String[] wordArray = str1.trim().split("\\s+");
    int wordCount = wordArray.length;

    System.out.println("Word count is = " + wordCount);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.