Results 1 to 18 of 18
  1. #1
    RSH
    RSH is offline Member
    Join Date
    Jun 2012
    Posts
    6
    Rep Power
    0

    Question Count Words in a String and Output First Four

    Greetings JF!

    I am new to Java and to programming in general. I am working on a program that will input a string and count the number of words in it. Then, if there are less than four words, it will output the four words. If there are four or more words, it will output the first four, and inform the user how many words were truncated.

    I've completed the word count section:


    import java.util.Scanner;
    public class WordCount

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

    String lineOfText;

    System.out.println("Please enter a line of text:");
    lineOfText = kb.nextLine();

    int i = 0, numberOfWords = 0;
    while (i < lineOfText.length())
    {
    if(lineOfText.charAt(i) == ' ')
    {
    numberOfWords++;
    }
    i++;
    }

    numberOfWords = numberOfWords + 1;
    //System.out.println("The number of words is: " + numberOfWords);

    At this point I think I need to have an if condition:

    if (numberOfWords<4)
    System.out.println("The words you have entered are: " + lineOfText);

    But this is inelegant: I am just repeating the entire string, not the words only. My guess is that I can use some kind of indexing method in order to break the string into substrings, and then to print those substrings. I am not quite sure how to do this. I have tried several times to no avail. I suppose I could also break the string up into arrays, but I'm not sure how to do that either.

    Would anyone mind helping me out with this one?

  2. #2
    lilezek is offline Member
    Join Date
    Jun 2012
    Posts
    23
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Java Code:
    String[] words = lineOfText.split(" ");
    numberOfWords = words.length(); // or words.size(), cannot remember.

  3. #3
    RSH
    RSH is offline Member
    Join Date
    Jun 2012
    Posts
    6
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Could you explain what that code will do?

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Count Words in a String and Output First Four

    lilezek seems to be making up things. His posted code has errors in it.

    The split() method will parse/split the String it is called on according to the regular expression passed to it as an argument.
    If there is only a single space between words, the example given above would work. If there can be more than one space between words then there needs to be a better reg exp.

    To see what the results of split are, use the Arrays toString() method to format the array for printing:
    Java Code:
          System.out.println("words="+Arrays.toString(words));
    Last edited by Norm; 06-12-2012 at 11:53 PM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    lilezek is offline Member
    Join Date
    Jun 2012
    Posts
    23
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Quote Originally Posted by RSH View Post
    Could you explain what that code will do?
    Sorry, I thought the name of the method "split" would be self-explainatory.

    That method splits into an array of Strings every token between each ocurrence of the REGEX expression.
    I sadly admit I don't know so much about REGEX, but all your words are separated by one space this would do the work.

  6. #6
    Ksharp is offline Banned
    Join Date
    Jun 2012
    Location
    Beijing,China
    Posts
    34
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    I tested it. @Norm is right, you need PRX to judge the number of words .Fortunately I am a little good at it .
    But Due to criticism from Jos and others , I only post a segment of my code.

    Java Code:
     System.out.println("Please enter a line of text:");
      String[] lineOfText = kb.nextLine().split("\\W+");
      int numberOfWord = lineOfText.length ;
      if ( numberOfWord <= 4 )  System.out.println(lineOfText) ;
      else {
          System.out.println("The first four words is: " + 
             lineOfText[0]+" "+lineOfText[1]+" "+lineOfText[2]+" "+lineOfText[3]);
          System.out.println("The number of words is: " + numberOfWord); }

    Ksharp

  7. #7
    RSH
    RSH is offline Member
    Join Date
    Jun 2012
    Posts
    6
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Thanks for all your help, guys. I still haven't entirely got the hang of arrays. Ksharp - when I tried your code it compiled fine, however, if the user enters four or less words, instead of printing the words, "[Ljava.lang.String;@1e4cbc4" is printed out. Do I need to convert the array to a string of some sort?

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Count Words in a String and Output First Four

    See the Arrays class's toString() method as a way to format the contents of an array for printing.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: Count Words in a String and Output First Four

    Yes.
    That is the memory address of the String[].
    Ksharp's code prints out the individual words in the array.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    RSH
    RSH is offline Member
    Join Date
    Jun 2012
    Posts
    6
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Works great. Thanks all for your help.

  11. #11
    Ksharp is offline Banned
    Join Date
    Jun 2012
    Location
    Beijing,China
    Posts
    34
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Oh. My bad. Just use the same statement for both scenario :
    lineOfText[0]+" "+lineOfText[1]+" "+lineOfText[2]+" "+lineOfText[3]



    Ksharp

  12. #12
    RSH
    RSH is offline Member
    Join Date
    Jun 2012
    Posts
    6
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    The problem with using lineOfText[0] + etc. for the scenario if numberOfWords is less than or equal to 4 is that lineOfText[1] or [2] or [3] may not exist. I think I got a compiler error when I tried this method.

    Instead I used Arrays.toString(lineOfText)); and printed that. Works great.

    Thanks again all for your help.

  13. #13
    vhonanivb is offline Member
    Join Date
    May 2012
    Posts
    7
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Why use arrays?

    Java Code:
     String name = "vhonani";
    		
    		if(name.length()< 4){
    			System.out.println("First four letters ");
    			for(int i=0;i<= name.length(); i++){
    				System.out.println(name.charAt(i));
    			}
    			 System.out.println("Number of word is : " + name.length());
    		}	
    		else if(name.length() >4){
    			System.out.println("First four letters ");
    			for(int i=0; i<=4; i++){
    				System.out.println(name.charAt(i));
    			}
    			System.out.println("Number of word is : " + name.length());
    		}

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: Count Words in a String and Output First Four

    @vhonanivb Did you test your code?
    What happens when the String name has < 4 characters in it?
    How many characters does it print when there are more than 4 characters in name?
    Why does it print a message saying it will display 4 characters if there are less than 4?
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: Count Words in a String and Output First Four

    Additionally, don't spoonfeed code, and especially don't spoonfeed bad code.
    Java Code:
    // if(name.length()< 4){
      // for(int i=0;i<= name.length(); i++){
        //  etc
      // }
    // } else if(name.length() >4){
      // for(int i=0; i<=4; i++){
        //  etc
      // }
    // }
    for (int i = 0; i < 4 && i < name.length(); i++){
      // etc
    }
    Why does it print a message saying it will display 4 characters if there are less than 4?
    And why does it print the first 5 characters if there are more than 4? Also, learn the meaning of "letter" and "word"

    Finally, this thread was started more than a month ago. Don't post to dead threads.

    db
    Last edited by DarrylBurke; 07-25-2012 at 04:21 PM.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  16. #16
    vhonanivb is offline Member
    Join Date
    May 2012
    Posts
    7
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Java Code:
    if(name.length()< 4){
               System.out.println("First letters ");
               for(int i=0;i<= name.length(); i++){
                   System.out.println(name.charAt(i));
               }
                System.out.println("Number of word is : " + name.length());
           }  
           else if(name.length() >4){
               System.out.println("First four letters ");
               for(int i=0; i<4; i++){
                   System.out.println(name.charAt(i));
               }
               System.out.println("Number of word is : " + name.length());
           }
    I missed a couple of things in my code , but I still feel my code is more efficient than the use of an array.

    Why use memory the is a way around it.
    Last edited by vhonanivb; 07-26-2012 at 10:52 AM.

  17. #17
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: Count Words in a String and Output First Four

    It also doesn't work if the name length is exactly 4.
    And will get an array index out of bounds exception if it's < 4.

    Oh, and it's only printing the first 4 characters...the OP wanted the first 4 words hence the split() and the String[].
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    vhonanivb is offline Member
    Join Date
    May 2012
    Posts
    7
    Rep Power
    0

    Default Re: Count Words in a String and Output First Four

    Oh yes.

    Sorry , I get it now.

    Thanks

Similar Threads

  1. count no of words in string
    By fakepics500 in forum New To Java
    Replies: 12
    Last Post: 07-19-2011, 10:49 AM
  2. Count Words
    By jjjkkk in forum New To Java
    Replies: 8
    Last Post: 07-18-2011, 01:24 PM
  3. Read text file and count words.
    By chdn202002 in forum New To Java
    Replies: 5
    Last Post: 07-17-2011, 02:44 PM
  4. Replies: 8
    Last Post: 02-04-2009, 08:55 PM
  5. Replies: 5
    Last Post: 11-22-2008, 01:34 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •