Results 1 to 20 of 20
  1. #1
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Question count occurence of word in a line of text

    which method should i use to count occurence of words in a line of text if i just learn till the string and text i/o this topic.Beside the hashmap,got another method to use?i m not really undestand about hashmap...

  2. #2
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default

    Not sure if I understnd your question, but one way is that you could use the string split() method to separte the words in an array and then cycle through the array looking (by comparing) for the string ocurrences.

    String API link:
    String (Java Platform SE 6)

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  3. #3
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Question

    can i do like this...it seems no errors but no counting occur at all...why?i dont know how to compare the words inside a line between each other...


    import java.util.*;

    public class Question3{
    public static void main(String[]args){

    Scanner scan=new Scanner(System.in);

    System.out.println("Enter a string:");
    String s=scan.nextLine();

    String[] words = s.split("[ ':.!?]");


    String a=words[0];

    int count=0;

    for (int i=1;i<words.length;i++){

    if (words[i].equals(a)){

    count++;

    a= words[i];
    }

    }

    for (int i=1;i<words.length;i++){
    System.out.print(words[i]+" "+count);
    System.out.println();
    }

    }
    }

  4. #4
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default A for within a for ...

    I think what you need is two loops... the first loop (outer) would cycle through the words in the array and the second (inner) loop would compare the words from the first loop to all the words in the array. I think it would be something like...
    Java Code:
    String word = "";
    for (int i=0;i<words.length;i++){
       word = words[i];
       for (int j=0;i<words.length;j++){
       if (words[j+1].equals(word)){
    .
    .
    .
    }
    }
    I would also to rename some of your variables... for example change variable "a" to "word", "words" to "wordArray", etc. give some meaning to the variables name.

    Luck,
    CJSL
    Last edited by CJSLMAN; 02-26-2009 at 06:05 PM. Reason: correct a typo
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  5. #5
    JVposter is offline Member
    Join Date
    Feb 2009
    Location
    Romania
    Posts
    11
    Rep Power
    0

    Default

    Quote Originally Posted by sinyi88 View Post
    which method should i use to count occurence of words in a line of text if i just learn till the string and text i/o this topic.Beside the hashmap,got another method to use?i m not really undestand about hashmap...
    StringUtils.countMatches("arthur", "r")

    You do not used hash map for this :
    please try read tutorials before puting questions

  6. #6
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default huh?

    Sorry JVPoster, but countMatches() is not a Java API method. It maybe a third party API, but it is not part of the Java API specification (at least I couldn't find it).

    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  7. #7
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default

    OK... so I'm curious about JVp's comment about using "StringUtils.countMatches()" and I decided to see where is it used. I opened Google and typed "java countmatch" and the first match that showed up was this:
    String count matches : String Utils**Apache Common**Java
    and guess what? it's extacly the same example that JVp posted. Now, to be able to use that method, you have to have had the following import statement:
    Java Code:
    import org.apache.commons.lang.StringUtils;
    So... JVp's suggestion is worthless and he just posted the first thing that he found on the web that looked similiar... and from his other posts (equally worthless), he's either a troll or trying to bump his post count up to 20.

    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  8. #8
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Question

    Enter a string:
    how are you
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Question3.main(Question3.java:24)
    Press any key to continue . . .

    how to initialise the count array?

    import java.util.*;

    public class Question3{
    public static void main(String[]args){

    Scanner scan=new Scanner(System.in);

    System.out.println("Enter a string:");
    String s=scan.nextLine();

    String[] words = s.split("[ ':.!?]");




    String word = "";
    int [] count=new int[100];
    for (int i=0;i<words.length;i++){

    word = words[i];

    for (int j=0;j<words.length;j++){

    if (words[j+1].equals(word)){
    count[j+1]++;
    System.out.println(words[i]+" "+count[j+1]);
    }
    }
    }

    }
    }

  9. #9
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default ooppss... sorry

    OK, I had an error... the array was running out of bounds becasue of the [j+1]... simple to fix...
    Java Code:
    for (int j=1;j<words.length;j++){
    and change all [j+1] to [J]

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  10. #10
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Question

    Enter a string:
    how do you do
    how 0
    do 2
    you 1
    do 2
    Press any key to continue . . .


    why the word "do" print 2 times?and the word "how" not counting...



    import java.util.*;

    public class Question3{
    public static void main(String[]args){

    Scanner scan=new Scanner(System.in);

    System.out.println("Enter a string:");
    String s=scan.nextLine();

    String[] words = s.split("[ ':.!?]");




    String word = "";
    int [] count=new int[100];
    for (int i=0;i<words.length;i++){

    word = words[i];

    for (int j=1;j<words.length;j++){

    if (words[j].equals(word))
    count[j]++;

    }
    }

    for (int x=0;x<words.length;x++){
    System.out.println(words[x]+"\t"+count[x]);
    }


    }
    }

  11. #11
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Quote Originally Posted by sinyi88 View Post
    why the word "do" print 2 times?
    Umm... because there's two of them? ;-)

    Quote Originally Posted by sinyi88 View Post
    and the word "how" not counting...
    The loop where you count the number of occurrences starts with j=1 so the first word is never compared with itself to get a count of 1.

  12. #12
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Thinking about this, if you really don't want "do" to be counted and reported twice then a map of some sort really is the easiest way to go.

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Or something like this in the loop that does the counting:

    Java Code:
    FOR j=0 j<words.length j++
        IF words[j].equals(word)
            increment count[i] (not j)
            IF i!=j
                make count[j]=0
    That way only the last of the counts for a given word will be nonzero.

  14. #14
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Default

    is it like this?i dont understand what u mean...sorry...still got errors although can run



    import java.util.*;

    public class Question3{
    public static void main(String[]args){

    Scanner scan=new Scanner(System.in);

    System.out.println("Enter a string:");
    String s=scan.nextLine();

    String[] words = s.split("[ ':.!?]");




    String word = "";
    int [] count=new int[20];
    for (int i=0;i<words.length;i++){

    word = words[i].toLowerCase();

    for (int j=0;j<words.length;j++){

    if (words[j].equals(word)){

    count[i]++;
    }
    if (i != j){
    count[j]=0;

    }
    }
    }


    for (int y=0;y<words.length;y++){

    System.out.println(words[y]+"\t"+count[y]);
    }





    }
    }

  15. #15
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    I have no idea what the errors might be unless you say.

    You have misplaced the if statement within the second for loop. To see how to correct it, think for a bit about what the algorithm is trying to do.

    Your original version updated the count every time it found two words the same. What I am suggesting is that it continues to do this - but that it should also "reset" the counts for all the other equal words.

    For instance when you count the occurrences in "How do you do" the counting would go like (each row represents one time round the outer for loop)

    Java Code:
    How do you do
    1   0  0    0 
    How do you do
    1   2  0    0 
    How do you do
    1   2  1    0 
    How do you do
    1   0  1    2
    The idea is that when you are counting all the words that are equal to the second "do" you reset the count for the first one back to zero.

    Then when you output the counts you can just ignore words with a zero count. (You are not doing this at the moment. You will have to change the second for loop so that the first occurrence of "do" - the one with count 0 - is not printed.)

    One small point - you should decide whether your string comparisons should be case sensitive or not and then stick to that. At the moment you are initialising word as the lower case version of the word in your original string, but then comparing it to the original within the inner for loop.

  16. #16
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Unhappy

    That's all i can do...but the print out got problems...i dont know how to avoid to print words that already printed...the 'do' still print 2 times...:(

    Enter a string:
    how do you do
    how 1
    do 2
    you 1
    do 1
    Press any key to continue . . .


    import java.util.*;

    public class Question3{
    public static void main(String[]args){

    Scanner scan=new Scanner(System.in);

    System.out.println("Enter a string:");
    String s=scan.nextLine();

    String[] words = s.split("[ ':.!?]");




    String word = "";
    int [] count=new int[20];
    for (int i=0;i<words.length;i++){

    word = words[i].toLowerCase();

    for (int j=1;j<words.length;j++){
    if (i != j){
    if (words[j].equals(word)){

    count[i]++;

    }
    }


    if (i == j){
    if (words[j].equals(word)){

    count[i]=1;

    }
    }

    if (!words[j].equals(words[0])){
    count[0]=1;
    }
    }
    }

    for (int y=0;y<words.length;y++){
    System.out.println(words[y]+"\t"+count[y]);
    }





    }
    }

  17. #17
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Unhappy Help!

    can somebody help me?reply me...:(

  18. #18
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    When you post code, highlight it and use the code button (lebelled #).

    Java Code:
    import java.util.*;
    
    public class Question3 {
        public static void main(String[]args){
    
            Scanner scan=new Scanner(System.in);
    
            System.out.println("Enter a string:");
            String s=scan.nextLine();
    
            String[] words = s.split("[ ':.!?]");
    
            String word = "";
            int [] count=new int[20];
            for (int i=0;i<words.length;i++){
    
                word = words[i].toLowerCase();
    
                for (int j=0;j<words.length;j++){
                        // first increment i's count for every
                        // equal word
                    if (words[j].toLowerCase().equals(word)){
                        count[i]++;
                            // then make sure the other instances of this
                            // word get a zero count
                        if (i != j){
                            count[j] = 0;
                        }
                    }
                }
            }
                // correct this loop so that it doesn't
                // print the zero counts
            for (int y=0;y<words.length;y++){
                System.out.println(words[y]+"\t"+count[y]);
            }
        }
    }
    I've given up and put the if statement where it should be, corrected the string comparison and changed the error reintroduced into the inner loop (j=0;...). But I've left you the output loop!

    Once you understand what is happening you might try to make it more efficient. (Would it help to change the words array so that it contained only lower case strings? Do we really need to check every word with every other - or is it enough to check every word with all those with a lower index?)

  19. #19
    sinyi88 is offline Member
    Join Date
    Feb 2009
    Posts
    19
    Rep Power
    0

    Smile

    i correct it already...it can be run now...thank you...but can u tell me how to sort the words alphabetically when printed out?

  20. #20
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    can u tell me how to sort the words alphabetically when printed out?
    (Just an aside: using a Map - which your OP said you didn't want to do - makes this trivial. A TreeMap for instance will store the counts for each word so that they can be accessed alphabetically without any extra code at all.)

    The alternative is to write a sorting algorithm that sorts both arrays alphabetically on the words array.

Similar Threads

  1. count character in text file as input file
    By aNNuur in forum New To Java
    Replies: 7
    Last Post: 03-25-2010, 04:01 PM
  2. Make a text in Jlabel down to next Line
    By hungleon88 in forum AWT / Swing
    Replies: 2
    Last Post: 12-01-2008, 11:10 PM
  3. Replies: 7
    Last Post: 11-19-2008, 02:09 PM
  4. saving to a new line a text
    By jadaleus in forum Advanced Java
    Replies: 1
    Last Post: 10-20-2008, 06:10 PM
  5. [SOLVED] what is text limit line?
    By Nicholas Jordan in forum NetBeans
    Replies: 12
    Last Post: 07-16-2008, 05:05 AM

Posting Permissions

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