Results 1 to 19 of 19
  1. #1
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Exclamation counting words within a file

    The problem I'm working on combines Unix and Java. I'm trying to create a Java program that can act exactly like the Unix command wc.
    I've already worked out counting the lines, and don't show that code here. What I need next is help figuring out why when I test my opW method, the answer is always 1. I've tried several tactics, and this is the only one I've gotten to do anything.
    I need to pass the method a file and then count the words within that file. Any suggestions would be wonderful.

    Java Code:
    public static int opW(String a) throws IOException
    	{
    		BufferedReader reader = new BufferedReader(new FileReader(a));
    		Scanner scan = new Scanner(a);
    		
    		while (reader.read() != -1)
    		{
    		String line = scan.nextLine();
    		String[] w = line.split(" ");
    			words = w.length;
    			System.out.println(words);
    		}
    
    		return 0;
        }
    public static void main(String []args)
    	{
    		Scanner cmd = new Scanner(System.in);
    		if (cmd.next().equals("wc"))
    		{
    			String option = cmd.next();
    			if (option.equals("-l"))
    			{
    				try {
    					opL(cmd.next());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (option.equals("-w"))
    			{
    				try{
    					opW(cmd.next());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			
    			}

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    my opW method, the answer is always 1.
    The only return statement I see in opW() returns 0. How do you get a value of 1?

    Can you post the output from your program showing what it prints?

    Also please add some comments to your code describing what it is doing. The opW method is confusing in the way it is coded. I have no idea what the code you have posted is supposed to do.
    Last edited by Norm; 07-25-2011 at 02:41 AM.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    You could add a little debugging code:

    Java Code:
    public static int opW(String a) throws IOException
    {
        BufferedReader reader = new BufferedReader(new FileReader(a));
        Scanner scan = new Scanner(a);
    		
        while (reader.read() != -1)
        {
            String line = scan.nextLine();
            [color=green]System.out.println("Read the line: " + line);[/color]
            String[] w = line.split(" ");
            words = w.length;
            System.out.println(words);
        }
        return 0;
    }
    [Edit] It is good practice to declare variables close to where you use them and not rely on "global" variables like words

  4. #4
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Default

    wc -w file
    1

    contents of file:
    apple
    pear
    bog
    java is awesome

  5. #5
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Default

    I didn't want to use it as a global variable, but I couldn't access it outside of the while loop. And if I declare it outside of the loop, I can't access it in the loop.

  6. #6
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    You say you want to count the words in a file and yet nowhere in your code do I see any counting.

    Btw calling the read method is not efficient and sometimes does not do what you expect. What you should do instead is call readLine and keep looping until it returns null.

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    Change your code to
    Java Code:
    System.out.println("The number of words in the file is " + opW(cmd.next()));

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Quote Originally Posted by justOne View Post
    I didn't want to use it as a global variable, but I couldn't access it outside of the while loop.
    You are only using it (printing it) within the while loop, so declare it there.

    So, did you add the line and see exactly what you were splitting to obtain the answer 1?

  9. #9
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Default

    It says the line it's reading is the name of the file???

    You say you want to count the words in a file and yet nowhere in your code do I see any counting.
    I assign the number of words in the array as the value of the int word.

    Java Code:
    String[] w = line.split(" ");
    			words = w.length;

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    If the OP would look at his code and add some comments about what each statement is doing he would see that the Scanner class is returning the String that was in its constructor.
    What is the Scanner class supposed to do?

  11. #11
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    Quote Originally Posted by justOne View Post
    I assign the number of words in the array as the value of the int word.
    That is assigning not counting. Imagine someone calls out a series of numbers. I write the first number down on a piece of paper. They call out the second number. I erase the first number and write down the second number. They call out the third number. I erase the second number and write down the third number. etc. At the end the only number I have written down would be the last number called. I do not have a count of all numbers.

    Heres a hint when you count something then you would use [insert mathematical operation].

  12. #12
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Default

    Norm, could you elaborate some? I'm not seeing it..

    Junky: Thanks, I changed it to
    Java Code:
    		BufferedReader reader = new BufferedReader(new FileReader(a));
    		Scanner scan = new Scanner(a);
    		
    		while (reader.readLine() != null)
    		{
    
    		String line = scan.nextLine();
    		System.out.println(line);
    		String[] w = line.split(" ");
    
    			for (int i=0; i<w.length; i++)
    			{
    				int words = 0;
    				words++;
    				System.out.println(words);
    			}
    			
    		}
    
    		return 0;

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    It says the line it's reading is the name of the file???
    It is saying, truthfully, that the line it has read is the filename. That is not a useful thing to be splitting.

    Get rid of the scanner and take seriously what Junky said earlier about using the readLine() method, because it *will* give you something worth splitting.

    [Edit] slow... ;(

  14. #14
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    :headdesk:

    You are not listening. If the point of the method is to count the number of words in a file then why does it always return 0?

    Look at your loop. Each time around you declare a variable, set it to zero, increment it. At the end the only value it can have is 1.

    Read the Java API for the Scanner class. You have attached your Scanner object to a String and not a File. Run this code and see what it does.
    Java Code:
    Scanner reader = new Scanner("My Text File.txt");
    while(reader.hasNext()) {
        System.out.println(reader.next());
    }

  15. #15
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Default

    Java Code:
    BufferedReader reader = new BufferedReader(new FileReader(a));
    Scanner scan = new Scanner(reader);
    
    while (scan.hasNext())
    {
    int words=0;
    String line = scan.nextLine();
    System.out.println("Line: " + line);
    String[] w = line.split(" ");
    for (int i=0; i<w.length; i++)	
    {
    words++;	
    System.out.println("Words# "+ words);
    }

    Line: apples pear bee
    Words# 1
    Words# 2
    Words# 3
    Line: water air wind fire
    Words# 1
    Words# 2
    Words# 3
    Words# 4

  16. #16
    justOne is offline Member
    Join Date
    Jul 2011
    Posts
    11
    Rep Power
    0

    Default

    I know I'm an idiot, and I see that what's happening is that it's reassigning each line into the array and replacing the previous, but I just don't see how to fix it.

  17. #17
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    So? Do you have a question?

    I have several issues:

    Wrapping a Scanner around a BufferedReader is overkill. You can use a Scanner OR a BufferedReader not both.

    Using hasNext in the loop condition and nextLine inside the loop may lead to unexpected behaviour.

    The for loop is pointless and can be replaced by: System.out.println(("Words# "+ w.length)

    Your code still only reports the value for the last line and does not count the entire file.

    Why does the method print a statement at all? The whole point of the method is to count the words in a file and that is it. It should return the count back to your main method where you can print it out like I did in reply #7.

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    12,998
    Blog Entries
    7
    Rep Power
    19

    Default

    Quote Originally Posted by justOne View Post
    [CODE]
    String[] w = line.split(" ");
    Don't split your lines like that; for two consecutive spaces) the split( ... ) method will asume an empty word between them; split as follows: line.split("\\s+"");

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    Now we get into debugging regular expressions. Hope to get the project working by next week.

Similar Threads

  1. Counting occurence of a word in file
    By KAS in forum New To Java
    Replies: 15
    Last Post: 05-16-2011, 06:47 PM
  2. Counting number of entries in a file
    By lenny0 in forum New To Java
    Replies: 3
    Last Post: 05-10-2011, 03:40 AM
  3. Counting Words
    By Shyamz1 in forum New To Java
    Replies: 9
    Last Post: 03-03-2011, 01:12 PM
  4. Counting words
    By Wasley in forum New To Java
    Replies: 9
    Last Post: 01-30-2011, 10:57 PM
  5. Counting specific word from a file
    By jaq in forum New To Java
    Replies: 2
    Last Post: 12-02-2009, 06:12 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •