Jump to content

Word Count problem

- - - - -

  • Please log in to reply
7 replies to this topic

#1
Jesp

Jesp

    Newbie

  • Members
  • Pip
  • 4 posts
I have this code
so far
but I have some trouble with the case ' '

public class WordCount {

private int numChars;

private int numWords;

private int numLines;


public WordCount()

{

numChars = 0;

numWords = 0;

numLines = 0;


}

public void wordCount(String f)

{

try

{

FileReader reader = new FileReader(f);

Scanner in = new Scanner (reader);

int lineAt = 1;

while(in.hasNextLine())

{

String line = in.nextLine();

int lineReade = line.length(); // read the string and count

lineRead += lineRead +1;

for(int j = 0; j+1 <lineRead; j++)

{

final char charValue = line.charAt(j);

if (charValue == ' ' && charValue != line.charAt(j+1))

numWords++;

if(charValue == '\n' && charValue != line.charAt(j+1))

numWords++;

}

numlines++;

lineAt++;

}

catch (FileNotFoundException e)

{

System.out.println("Error" + e);

}

}

}


I think this is implemented right but i get a
error message att ' ' char

my main method needs
to print in the terminal one of these commands
-l number of lines
-w number of words
-n number of chars

with a filename

if the user doesent print any of these commands it just
gives them all.
but im not sure how to do this

so it would for example be in terminal window:
-w test.txt
and it would print out the sum of all the words in that file
my main class so far is:


public class WordCountMain{

public static void main (String [] args) {

Scanner console = new Scanner(System.in);

System.out.println("OPTION"  + 

                              " -n print the chars" +

                              " -l print the lines"  +

                              " -w print the words");

System.out.print("enter a file name and a Option");

String inputFileName = console.next();


WordCount w = new WordCount();

w.wordCount(inputFileName);

System.out.print(w.getNumberOfLines()+""+w.getCharNumber()+""+w.getWordNumber()+""+inputFileName);


}

}


[/code]

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
This code compiles and runs:

public void wordCount(String f) {

        try {

            FileReader reader = new FileReader(f);

            Scanner in = new Scanner(reader);

            int lineAt = 1;

            while (in.hasNextLine()) {

                String line = in.nextLine();

                int lineRead[COLOR="red"][B]e[/B][/COLOR] = line.length(); // read the string and count  [COLOR="red"]typo there[/COLOR]

                [B][COLOR="red"][COLOR="red"]lineRead += lineRead +1;[/COLOR] ---> Remove this line![/COLOR][/B]

                for (int j = 0; j + 1 < lineRead; j++) {

                    final char charValue = line.charAt(j);

                    if (charValue == ' ' && charValue != line.charAt(j + 1))

                        numWords++;

                    if (charValue == '\n' && charValue != line.charAt(j + 1))

                        numWords++;

                }

                num[B][COLOR="red"]L[/COLOR][/B]ines++; //[COLOR="red"][B]typo there[/B][/COLOR]

                lineAt++;

            [COLOR="red"][B]} Forgot this accolade[/B][/COLOR]

        } catch (FileNotFoundException e) {

            System.out.println("Error" + e);

        }

    }


Are you sure it must be in the main that you ask for those parameters, and not upon starting the program you allready give the parameters?
like if you've build the program in program.jar
c:\programs\>java program.jar -l -w fileName
?

Other notes:
  • You don't count chars yet
  • You count words wrong. You count spaces, that's not the same. If i end a word with a newline it's no space, but i will start another word on the next line.


#3
Jesp

Jesp

    Newbie

  • Members
  • Pip
  • 4 posts
Yes im sure that the main is where i ask those parameters
but im not sure how to implement it in that way

count chars you count the length of a file right
all the strings?

okey what is it that need to be change in that way with the word part?

Also sorry for the typo error
should have corrected it before posting
my bad

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Here's a good wordcount. Short and simple.
public void wordCount(String f) {
        try {
            FileReader reader = new FileReader(f);
            Scanner in = new Scanner(reader);
            while (in.hasNextLine()) {
                String line = in.nextLine().trim();
                numWords += line.split(" ").length;
                numLines++;
                numChars += line.line.replaceAll("\r \n\t", "").length();        //get rid of all spaces, newlines(\n), carriage returns(\r) and tabs (\t) ... basicly all characters you don't see and shouldn't be counted.
            }
        } catch (FileNotFoundException e) {
            System.out.println("Error" + e);
        }
    }

For numChars i also included special symbols like periods, dashes, slashes, brackets. If you wish to only count letters and numbers. Loop trough all the characters of each line and do
if(Character.isLetterOrDigit(char)){
  numChars++;
}

Your main should look as followed:
public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.println("OPTION" +
                " -n print the chars" +
                " -l print the lines" +
                " -w print the words");
        System.out.print("enter a file name and a Option");
        String[] input = console.nextLine().split(" ");

        WordCount w = new WordCount();
        if (input.length == 0) {
            System.exit(1);
        }
        w.wordCount(input[0]);
        System.out.println("reading " + input[0]);
        if (input.length == 1) {
            System.out.print("lines: " +w.getNumberOfLines() + "\nchars: " + w.getCharNumber() + "\nwords: " + w.getWordNumber());
        } else {
            for (int i = 1; i < input.length; i++) {
                if (input[i].equals("-n")) {
                    System.out.println("chars: " +w.getCharNumber());
                } else if (input[i].equals("-l")) {
                    System.out.println("lines: " +w.getNumberOfLines());
                } else if (input[i].equals("-w")) {
                    System.out.println("words: " +w.getWordNumber());
                }
            }
        }
    }


#5
Jesp

Jesp

    Newbie

  • Members
  • Pip
  • 4 posts

oxano said:

Here's a good wordcount. Short and simple.

public void wordCount(String f) {

        try {

            FileReader reader = new FileReader(f);

            Scanner in = new Scanner(reader);

            while (in.hasNextLine()) {

                String line = in.nextLine().trim();

                numWords += line.split(" ").length;

                numLines++;

                numChars += line.line.replaceAll("\r \n\t", "").length();        //get rid of all spaces, newlines(\n), carriage returns(\r) and tabs (\t) ... basicly all characters you don't see and shouldn't be counted.

            }

        } catch (FileNotFoundException e) {

            System.out.println("Error" + e);

        }

    }


For numChars i also included special symbols like periods, dashes, slashes, brackets. If you wish to only count letters and numbers. Loop trough all the characters of each line and do

if(Character.isLetterOrDigit(char)){

  numChars++;

}


Your main should look as followed:

public static void main(String[] args) {

        Scanner console = new Scanner(System.in);

        System.out.println("OPTION" +

                " -n print the chars" +

                " -l print the lines" +

                " -w print the words");

        System.out.print("enter a file name and a Option");

        String[] input = console.nextLine().split(" ");


        WordCount w = new WordCount();

        if (input.length == 0) {

            System.exit(1);

        }

        w.wordCount(input[0]);

        System.out.println("reading " + input[0]);

        if (input.length == 1) {

            System.out.print("lines: " +w.getNumberOfLines() + "\nchars: " + w.getCharNumber() + "\nwords: " + w.getWordNumber());

        } else {

            for (int i = 1; i < input.length; i++) {

                if (input[i].equals("-n")) {

                    System.out.println("chars: " +w.getCharNumber());

                } else if (input[i].equals("-l")) {

                    System.out.println("lines: " +w.getNumberOfLines());

                } else if (input[i].equals("-w")) {

                    System.out.println("words: " +w.getWordNumber());

                }

            }

        }

    }

thank you oxano
I do get some problems though
Ive created a test.txt file

"Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities"

and run it by using test.txt -w
i get
0 words from the command window
am i running it wrong or is it something else

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I get 55 words here. Could you post all the code you have? (and make sure the txt-file is correct :P)

#7
Jesp

Jesp

    Newbie

  • Members
  • Pip
  • 4 posts
Its probably the file
im using the code you posted
and saved a file as test.txt
containing the text.


public void wordCount(String f) {

        try {

            FileReader reader = new FileReader(f);

            Scanner in = new Scanner(reader);

            while (in.hasNextLine()) {

                String line = in.nextLine().trim();

                numWords += line.split(" ").length;

                numLines++;

                numChars += line.line.replaceAll("\r \n\t", "").length();        //get rid of all spaces, newlines(\n), carriage returns(\r) and tabs (\t) ... basicly all characters you don't see and shouldn't be counted.

            }

        } catch (FileNotFoundException e) {

            System.out.println("Error" + e);

        }



public static void main(String[] args) {

        Scanner console = new Scanner(System.in);

        System.out.println("OPTION" +

                " -n print the chars" +

                " -l print the lines" +

                " -w print the words");

        System.out.print("enter a file name and a Option");

        String[] input = console.nextLine().split(" ");


        WordCount w = new WordCount();

        if (input.length == 0) {

            System.exit(1);

        }

        w.wordCount(input[0]);

        System.out.println("reading " + input[0]);

        if (input.length == 1) {

            System.out.print("lines: " +w.getNumberOfLines() + "\nchars: " + w.getCharNumber() + "\nwords: " + w.getWordNumber());

        } else {

            for (int i = 1; i < input.length; i++) {

                if (input[i].equals("-n")) {

                    System.out.println("chars: " +w.getCharNumber());

                } else if (input[i].equals("-l")) {

                    System.out.println("lines: " +w.getNumberOfLines());

                } else if (input[i].equals("-w")) {

                    System.out.println("words: " +w.getWordNumber());

                }

            }

        }

    }



#8
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You did create the get-methods, right?
Like
public int getWordNumber() {
     return numWords;
}
And otherwise you'll have to debug trough it ;)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users