import java.util.*;
import java.lang.*;
import java.io.*;

class wordOccur
{
      public static void main(String[] a)throws Exception
      {
          int i;
          int[]f=new int[20];
          System.out.println("Enter the Sequence of the String:");
          Scanner s=new Scanner(System.in);
          for(i=0;i<f.length;i++)
          f[i]=0;
          String t=s.nextLine();
          count(t);
      }
      static void count(String t)
      {
          int[] f=new int[14];
          int i;
          String d=" ";
          String[] temp=t.split(d);
          for(i=0;i<temp.length;i++)
          {
              System.out.println(temp[i]);
              int l=temp[i].length();
              f[l]++;
          }
          for(i=1;i<f.length;i++)
          System.out.println(+ i +"  "+f[i]+" ");
      }
}

How to input a file (words.txt) and print to the screen a table indicating how many one-letter words, two-letter words, three-letter words, etc...
For example:File: This is a test for a java program.
output
1 2
2 1
3 1
4 3
5 0
6 0
7 1
stopping with the longest word and ignoring characters like ?!$#% these
If someone could explain or fix my code that would be great! thanks

Recommended Answers

All 5 Replies

Can you explain what your code does now, show its output and explain what the problem with it is?

The output looks like this:
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0

I know how to use a string but not sure how or where to input a file and have it read each word in the file.

Where does your code read from a file? How is it getting the input words that your code is supposed to count?
I'd start with that.
Read lines from a file and print them out.

When you can do that, work on reading individual words and print them out.
Then add logic to get the length of each word and print that out.

Try doing those simple steps first.

The output looks like this:
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0

I know how to use a string but not sure how or where to input a file and have it read each word in the file.

Also have a look here for reading in a file word by word:http://stackoverflow.com/questions/4574041/read-next-word-in-java... Then just get each words length and have an if statement to print out the length of each words that match your circumstances

or read a line as a String and use the split method to get an array based on that String.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.