Talha Shah Talha Shah -4 years ago 85
Java Question

if statement not adding value to my counter in word count program

I have a java program that reads a txt file and counts the words in that file. I setup my program so the String read from the txt file is saved as an ArrayList, and my variable word contains that ArrayList. The issue with my code is that my if statement does not seem to add a value to my count variable each time it detects space in the word string, it seems to only run the if statement once. How can I make it so the if statement finds a space, adds a +1 to my counter value, removes the space, and looks for the next space in the word variable's string? Here is the code:

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

public class FrequencyCounting
public static void main(String[] args) throws FileNotFoundException
// Read-in text from a file and store each word and its
// frequency (count) in a collection.
Scanner inputFile = new Scanner(new File("phrases.txt"));
String word= " ";
Integer count = 0;

List<String> ma = new ArrayList<String>();


inputFile.hasNextLine()) {
word = word + inputFile.nextLine() + " ";
if(word.contains(" ")) {
ma.remove(" ");
System.out.println("does contain");
else {
System.out.println("does not contain");

// Output each word, followed by a tab character, followed by the
// number of times the word appeared in the file. The words should
// be in alphabetical order.
; // TODO: Your code goes here.


When I execute the program, I get a value of 1 for the variable count and I get a returned string representation of the txt file from my phrases.txt

phrases.txt is :

my watch fell in the water
time to go to sleep
my time to go visit
watch out for low flying objects
great view from the room
the world is a stage
the force is with you
you are not a jedi yet
an offer you cannot refuse
are you talking to me

Answer Source

Your if statement is not inside any loop, so it will only execute once.

A better approach, which would save a shit ton of runtime, is to read each line like you already do, use the String.split() method to split it on spaces, then add each element of the returned String[] to your list by using the ArrayList.addAll() method (if that one exist, otherwise (optionally, ensure the capacity and) add the elements one by one).

Then count by using the ArrayList.size() method to get the number of elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download