My code is using the read() function to "read" through a txt file one character at a time and needs to internally count the number of lines, words, and characters.
Definitions of what is considered a line, word, and character:
of characters = any character that is "read" even if it is a 'whitespace' character
of lines = whenever the whitespace character '\n' is read.
of words = whenever a non-whitespace character is read that is either the first word OR one that is preceded by a whitespace character
*** I used Character.isWhitespace() method to determine if the current character is a whitespace or not.
import java.io.*;
import java.util.LinkedList;
public class UnixCommands{
public int[] wc(Reader in) throws IOException {
int[] result = new int[3];
int countChar = 0;
int countWord = 0;
int countLine = 0;
int savedD = -1;
int data = in.read();
while (data != -1) {
countChar++; //countChar no matter what.
if(data == '\n') { //countLine if '\n' is read.
countLine++;
}
if((countWord == 0 && !Character.isWhitespace(data)) ||
// first word appears
(!Character.isWhitespace(data) && Character.isWhitespace(savedD)))
//anytime another word appear.
{
countWord++;
}
savedD = data;
data = in.read();
}
result[0] = countLine;
result[1] = countWord;
result[2] = countChar;
System.out.println(countLine);
System.out.println(countWord);
System.out.println(countChar);
System.out.println(result);
return result;
}
}
Input: I am giving it a text file.
Output:
63852 -> count of lines
562492 -> count of words (i think my number of words is off by 1 word)
3202326 -> count of characters
[I@63b719 -> not sure why my result array is outputting this
I guess the question is why is not outputting the appropriate number of words?