2

This is my code to work out the length of a word:

public class WordCount {
public static void main (String args []) {
    String text;
    text = "Java";
    System.out.println (text);

    //Work out the length
            String [] input = text.split(" ");
            int MaxWordLength = 0;
            int WordLength = 0;
                for (int i = 0; i < input.length; i++)
                {  
                    MaxWordLength = input[i].length();
                    WordLength = MaxWordLength;                         
                } //End of working out length

                //Work out no. of words
                int[] intWordCount = new int[WordLength + 1];
                for(int i = 0; i < input.length; i++) {
                    intWordCount[input[i].length()]++; }

                for (int i = 1; i < intWordCount.length; i++) {
                    System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
                }
        }
    }

The problem I am having is that when it prints out the length of the word, I get these results:

Java
There are 0 words of length 4
There are 0 words of length 4
There are 0 words of length 4
There are 1 words of length 4

But when I change the text to "J" this prints out:

J
There are 1 words of length 1

Any idea why it's doing that? P.S. I'm kind of new to Java and any help would be appreciated.

6 Answers6

1

Let's walk through this:

public class WordCount {
public static void main (String args []) {
    String text;
    text = "Java";

text is equal to "Java".

    System.out.println (text);

Prints "Java"

    //Work out the length
            String [] input = text.split(" ");

This splits the string "Java" on spaces, of which there are none. So input (which I'd recommend be renamed to something more indicative, like inputs) is equal to an array of one element, and that one element is equal to "Java".

            int MaxWordLength = 0;
            int WordLength = 0;
                for (int i = 0; i < input.length; i++)
                {  
                    MaxWordLength = input[i].length();

For each element, of which there is only one, MaxWordLength is set to the length of the first (and only) element, which is "Java"...whose length is 4.

                    WordLength = MaxWordLength;                         

So WordLength is now equal to 4.

                } //End of working out length

                //Work out no. of words
                int[] intWordCount = new int[WordLength + 1];

This creates an int array of [WordLength + 1] elements (which is equal to [4 + 1], or 5), where each is initialized to zero.

                for(int i = 0; i < input.length; i++) {
                    intWordCount[input[i].length()]++; }

For each element in input, of which there is only one, this sets the input[i].length()-th element--the fifth, since input[i] is "Java" and it's length is four--to itself, plus one (because of the ++).

Therefore, after this for loop, the array is now equal to [0, 0, 0, 0, 1].

                for (int i = 1; i < intWordCount.length; i++) {
                    System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);

So this naturally prints the undesired output.

                }
        }
    }

Your output is different when the input is only "J", because the intWordCount array is shortened to input[i].length() elements, which is now 1. But the value of the last element is still set to "itself plus one", and "itself" is initialized to zero (as all int-array elements are), and then incremented by one (with ++).

aliteralmind
  • 19,847
  • 17
  • 77
  • 108
1

I am not sure if you want to count letter or word because your code counts letter to me.

Just you need to change this line from

String [] input = text.split(" ");

to

String [] input = text.split("");

and your program works perfectly.

input: Java

output: There are 4 letters of length 1 <- Hope this is the expected result for you

Source: Splitting words into letters in Java

You can achieve this in better and less headache by using Lambda in Java

Code:

import java.util.*;

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

         String[] st = "Hello".split("");
         Collection myList = Arrays.asList(st);
         System.out.println("your word has " + myList.stream().count() + "letters");

    } 
}

Output:

your word has 5 letters CLEARLY in length 1

My answer when you cleared what your issue is

Code:

public class WordCount      
{
    public static void main (String[] args)
    {
      String text ="";
      int wordLenght = 0;
      text = "Java is awesome for Me";
      System.out.println (text);


            String [] input = text.split(" ");
            List<Integer> list = new ArrayList<>();

            for (int i = 0; i < input.length; i++)
                {  
                    list.add(input[i].length());

                } 
            Set<Integer> unique = new HashSet<Integer>(list);

           for (Integer length : unique) {
               System.out.println("There are " + Collections.frequency(list, length) + " words of length " + length);
}
    } 
}

output:

  There are 2 words of length 2
  There are 1 words of length 3 
  There are 1 words of length 4 
  There are 1 words of length 7

Note: Read about HashSet and Set in Java

Source: http://javarevisited.blogspot.com/2012/06/hashset-in-java-10-examples-programs.html

Community
  • 1
  • 1
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • 1
    I want it to count the word. For example, if the text = "My name is" It should print out there are 1 words of length 4 there are 2 words of length 2 –  Jul 17 '14 at 15:22
  • k it is clear what u want now, so I'll edit my answer for u latter cuz I'm at work – Kick Buttowski Jul 17 '14 at 15:54
  • but in meantime work on what u have here cuz I believe u r almost there – Kick Buttowski Jul 17 '14 at 15:55
  • I have focused on the work out length part of my program and I have found that when I name my text to "my name is", the output only prints length of "is". So, it prints out "there are 0 words of length 2" It'something to do with the text.split –  Jul 17 '14 at 16:05
  • @Mordor I posted up what you want lemme know if it works for you – Kick Buttowski Jul 17 '14 at 20:05
  • This is what I wanted and I haven't come across the HashSets yet. So, I kind of tried writing the code with only Arrays. But, I read the link that you posted and it gave me an alternate and easier way to get rid of duplicates and store objects. Thank you Sir, I appreciate the help :) –  Jul 17 '14 at 22:07
  • I do not know what alternative way you found that , yet there is no way that you can solve this without using set collections. To me it will getting complicated can you share your answer so I can learn too? – Kick Buttowski Jul 17 '14 at 22:16
0
for (int i = 1; i < intWordCount.length; i++) {
    System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
}

1) You print out words with intWordCount[i] == 0, which is why you have the "There are 0 words of length X"
2) System.out.println("There are " ... + MaxWordLength); should probably be System.out.println("There are " ... + i);, so you have "There are 0 words of length 1" , "There are 0 words of length 2", etc

Kevin L
  • 1,066
  • 3
  • 12
  • 21
0

I know this question has been solved long time ago, but here is another solution using new features of Java 8. Using Java streams the whole exercise can be written in one line:

Arrays.asList(new String[]{"Java my love"}) //start with a list containing 1 string item
            .stream() //start the stream
            .flatMap(x -> Stream.of(x.split(" "))) //split the string into words
            .map((String x) -> x.length()) //compute the length of each word
            .sorted((Integer x, Integer y) -> x-y) //sort words length (not necessary)
            .collect(Collectors.groupingBy(x -> x, Collectors.counting())) //this is tricky: collect results to a map: word length -> count
            .forEach((x,y) -> {System.out.println("There are " + y + " word(s) with " + x + " letter(s)");}); //now print each result

Probably in few year time this would be a preferred method for solving such problems. Anyway it is worth knowing that such alternative exists.

haddr
  • 2,988
  • 1
  • 16
  • 16
  • 1
    I hardly think this is what he is asking. Please try and help him figure out what is wrong with his code instead of re-writing. – Bren Sep 04 '14 at 02:27
  • It's true, but the proper explanation has been given one post above. Instead of repeating, this is rather an alternative approach which might still come in handy for someone. – haddr Sep 05 '14 at 00:35
0

To count words in text with we used Pattern class with while loop:

I. Case Sensitive word counts

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountWordsInText {

    public static void main(String[] args) {
        String paragraph = "I am at office right now."
                + "I love to work at office."
                + "My Office located at center of kathmandu valley";
        String searchWord = "office";
        Pattern pattern = Pattern.compile(searchWord);
        Matcher matcher = pattern.matcher(paragraph);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println(count);

    }

}

II. Case Insensitive word counts

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountWordsInTextCaseInsensitive {


    public static void main(String[] args) {
        String paragraph = "I am at office right now."
                       + "I love to work at oFFicE."
                       +"My OFFICE located at center of kathmandu valley";
        String searchWord = "office";
        Pattern pattern = Pattern.compile(searchWord, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(paragraph);
        int count = 0;
        while (matcher.find())
            count++;
        System.out.println(count);

    }

}
Bhuwan Prasad Upadhyay
  • 2,916
  • 1
  • 29
  • 33
-1

Idk, but using the length method as much as you have to figure out how the length mechanism works is like defining a word using the word. It's an honorable conquest figuring out how the length method works, but you should probably avoid using the length method.

  • 1
    This is the first criticism I've ever heard levelled against the "String.length()" function. Would love to hear your reasonings. – aliteralmind Jul 16 '14 at 22:06
  • @aliteralmind I am so happy to see a person to vote down somebody with a comment and changeling them. thank you :) everbody votes down without any reason, yet you give a chance to the person to come up with better reslut – Kick Buttowski Jul 16 '14 at 22:15
  • Well, that's two firsts in quick succession :) Glad to be of service! – aliteralmind Jul 16 '14 at 22:27
  • I'm not criticizing the length function, I'm criticizing his methods on how to define the length function, which is essentially what his program is attempting to do, "This is my code to work out the length of a word:"..aka String.length().. – newsomedenzell Jul 17 '14 at 14:28