1

Hi guys I'm writing a method which counts words in a file, but apparently there is a mistake somewhere in the code and the method does not work. Here's my code:

public class Main2 {

    public static void main(String[] args) {

    count("/home/bruno/Desktop/WAR_JEE_S_09_Podstawy/MojPlik");

    }

    static int count(String fileName){
        Path path = Paths.get(fileName);
        int ilosc = 0;
        String wyjscie = "";
        try {
            for (String charakter : Files.readAllLines(path)){
                wyjscie += charakter;

            }
            StringTokenizer token = new StringTokenizer(wyjscie," \n");


        } catch (IOException e) {
            e.printStackTrace();
        }

        return ilosc;
    }

}

The file path is correct, here is the file content

test test
test
test

after i call the method in main it displays nothing. Where is the mistake ?

Bruno
  • 92
  • 1
  • 8

3 Answers3

1

Your code would count lines in a file ... well, if you followed up on that thought.

Right ow your code is simply reading lines, putting them into one large string, to then do nothing about the result of that operation. You have a single int counter ... who is init'ed to 0, and then just returned without ever being used/increased! And unless I am mistaken, readAllLines() will automatically remove the newline char in the end, so overall, your code is nothing but useless.

To count words you have to take each line and (for example) split that one-line-string for spaces. That gives you a number. Then add up these numbers.

Long story short: the real answer here is that you should step back. Don't just write code, assuming that this will magically solve the problem. Instead: first think up a strategy (algorithm) that solves the problem. Write down the algorithm ideas using a pen and paper. Then "manually" run the algorithm on some sample data. Then, in the end, turn the algorithm into code.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

Also, beside that you does not output anything, there is a slight error behind you logic. I have made a few changes here and there to get your code working.

s.trim() removes any leading and trainling whitespace, and trimmed.split("\\s+") splits the string at any whitespace character, including spaces.

static int count(String fileName) throws IOException {
    Path path = Paths.get(fileName);
    int count = 0;

    List<String> lines = Files.readAllLines(path);

    for (String s : lines) {
        String trimmed = s.trim();
        count += trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
    }

    return count;
}
Glains
  • 2,773
  • 3
  • 16
  • 30
0

Here is the code using functional-style programming in Java 8. This is also a common example of using Stream's flatMap - may be used for counting or printing words from a file.

long n = Files.lines(Paths.get("test.txt"))
              .flatMap(s -> Stream.of(s.split("\\s+")))
              .count();
System.out.println("No. of words: " + n);

Note the Files.lines(Path) returns a Stream<String> which has the lines from the input file. This method is similar to readAllLines, but returns a stream instead of a List.

prasad_
  • 12,755
  • 2
  • 24
  • 36