1

I was given a homework in which I need to count the number of words in a file and output how many words are the same. Like "a" in the whole text maybe it was repeated 350 times. I hope you get my point.

Now, im trying to do some tests and created a file("test.txt") containing:

Im a good boy
Hello World
A happy world it is

What I'm trying to do is storing it into an array to be able to count the words in the file. But I'm having a hard time. This is what i got so far.

void readFile() {
    System.out.println("Gi navnet til filen: ");
    String filNavn = sc.next();

    File k = new File(filNavn);
    try {
        Scanner sc2 = new Scanner(k);
        while (sc2.hasNextLine()) {
            String line = sc2.nextLine();
            String[] m = line.split(" ");
            String x = m[0];

            System.out.println(x);
        }  
    } catch (FileNotFoundException e) {
        System.out.print("mmm");
    }
}

but this only outputs the first words on the line.

What I would like to see is the same as the text file. But stored in an array. How can I do it?

Im a good boy
Hello World
A happy world it is 
kiheru
  • 6,588
  • 25
  • 31
  • Please untag JavaScript, as this is Java only, not dealing with JavaScript they are completely different languages. http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java – mswieboda Sep 30 '13 at 21:34

2 Answers2

1

This will only print out the first word because of this

String[] m = line.split(" ");
String x = m[0];
System.out.println(x);

Here you are only assigning the first word in the array (created by your split) to the variable x and then printing only that word.

To print all the words you will need to loop the array like so

for(int i = 0; i < m.length; i++)
{
     System.out.println(m[i]);
}

And to print the same as the file you could use System.out.print(). Note you will need to put the spaces back in and also account for the new lines. Below is one approach:

for(int i = 0; i < m.length; i++)
{
     if(i == m.length - 1)
         System.out.print(m[i] + "\n");
     else
         System.out.print(m[i] + " ");
}
Java Devil
  • 10,629
  • 7
  • 33
  • 48
0

Since your post didn't say you HAD to do it in Java (although I am guessing that is the case), I offer this:

perl -e 'while(<STDIN>) { map { $w->{lc($_)}++; } split("\\s", $_); } map { print "$_ $w->{$_}\n"; } keys %{$w} ;' < test.txt
Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33