Results 1 to 12 of 12
Like Tree1Likes
  • 1 Post By Junky

Thread: Character Occurence

  1. #1
    DMKanz is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Character Occurence

    I am new to java and I have an assignment that asked me to count the number of character and the number of occurrence. I have figured out the character count be I am not sure how to figure the number of occurrence. Can someone point me in the right direction? Here is my code so far..

    Thanks in advance

    Java Code:
    // Import Java libraries
    import java.io.*; // Makes all classes available from the io package
    import java.util.*; // Makes all classes available from the util package
    
    //Create class CharacterEntry
    public class CharacterEntry
    {
    	// Main method begins execution of Java application
    	public static void main(String[] args) throws IOException
    	{
    		// Declare variables
    		int characters = 0; 
    		int lines = 0;
    		String line;
    		
    		File openFile = new File("File.txt"); // Create file object based on reference to a file
    		Scanner readFile = new Scanner(openFile); // Open the file with the scanner
    
    		// Loop through the file
    		while (readFile.hasNext())
    		{
    			line = readFile.nextLine(); // Read the next line
        		lines++; // Count lines
        		
        		// Check for character : omits spaces
        		for (int i = 0; i < line.length(); i++)
        		{
        			if (!Character.isWhitespace(line.charAt(i)))
        			characters++; // Count characters
        		}
    		}
        
    		// Display character and line count
    		System.out.println("Number of characters: " + characters);
    		System.out.println("Number of lines: " + lines);
        
    		readFile.close(); // Close file stream
    
    		System.exit(0); // Terminate program
    	} // End main method
    } // End class CharacterEntry

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

    Default Re: Character Occurence

    What do you mean by occurrence? Do you mean you want to count how many a's, how many b's etc?

  3. #3
    DMKanz is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Character Occurence

    Junky - yes I need to count the number of occurrences for each letter

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

    Default Re: Character Occurence

    Are you trying to count how many times each character occurs?

    In that case you could use a Map<Character,Integer>. The key of a map entry would be the character you found as line.charAt(i) and its value would be the count. Each time you find a character you would increment the count (or, if it there is no map entry for that character yet you would create one with a count of 1).

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

    Default Re: Character Occurence

    If a Map is too advanced I have some clues:

    Array
    System.out.println('z' - 'a');

  6. #6
    DMKanz is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Character Occurence

    Ok - i am researching. With my current code will i be able to use an array. How do i read the letter into the array?

    Thanks in advance

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

    Default Re: Character Occurence

    You don't read the letter into the array. You use the array to store the totals for each letter. Total for 'a' goes into index 0, total for 'b' goes into index 1,.... total for 'z' goes into index 25. My hint above should help.

  8. #8
    DMKanz is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Character Occurence

    Sorry! I am real new to Java - but how does it know it is the letter 'a' or 'b'? - how do i get the character count into the array?

    Thank you for your patience

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

    Default Re: Character Occurence

    Did you see my hint above? Did you place it in a small test program to see what it does. Here comes the choo-choo train:
    Java Code:
    class Test {
        public static void main(String[] args) {
            char one = 'a';
            char two = 'b';
            char three = 'z';
            int index = one - 'a';
            System.out.println(index);
            index = two - 'a';
            System.out.println(index);
            index = three - 'a';
            System.out.println(index);
        }
    }

  10. #10
    DMKanz is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Character Occurence

    Junky - thank you I figured it out.

    I do have one more question is there a way to replace multiple characters without using \\W

    Java Code:
    String st = str.replaceAll("\\W", "");
    String lower = st.toLowerCase()
    I would like to replace , : ' ? ; . - with a space

    Thanks

  11. #11
    DMKanz is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Character Occurence

    Final code - any advise would be greatly appreciated

    Java Code:
    import java.io.*;
    import java.util.*;
    
     
    public class CharacterEntry
    {
    	public static void main(String[] args) throws Exception
    	{
    		
    		
    		int characters = 0; 
    		String line;
    		
    		File openFile = new File("File.txt"); 
    		Scanner readFile = new Scanner(openFile); 
    
    		
    		while (readFile.hasNext())
    		{
    			line = readFile.nextLine(); 
        		
        		
        		for (int i = 0; i < line.length(); i++)
        		{
        			if (!Character.isWhitespace(line.charAt(i)))
        			characters++; 
        		}
    		}
    		
    		System.out.println("There are " + characters +" characters in the text.");
    		readFile.close(); 
    		
    		FileInputStream fis = new FileInputStream("File.txt");
    		DataInputStream din = new DataInputStream(fis);
    		BufferedReader br = new BufferedReader(new InputStreamReader(din));
    		
    		String strLine = "";
    		String str = "";
    		 
    			while ((strLine = br.readLine()) != null)
    			{
    				str += strLine;
    			}
    			
    		String st = str.replaceAll("\\W", "");
    		String lower = st.toLowerCase();
    		
    		char[]character = lower.toCharArray();
    			Arrays.sort(character);
    				for(int counter = 0; counter < character.length; counter++)
    				{
    					char ch = character[counter];
    				
    					int count = 0;
    						for ( int i = 0; i < character.length; i++)
    						{
    							if (ch == character[i])
    								count++;
    						}
     			
    						boolean flag = false;
    				
    						for(int j = counter - 1; j >= 0; j--)
    						{
    							if(ch == character[j])
    								flag=true;
    						}
    							if(!flag)
    							{
    								System.out.println("Character " + ch + " appears " + count + " times");
    							}
    				}
    				
    				System.exit(0); 
     	}
     }
    Last edited by DMKanz; 10-21-2011 at 02:50 AM.

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

    Default Re: Character Occurence

    Do not read the file twice. Doing IO operations are expensive. Read a line once. You can then iterate over it once and do all the necessary checks. Or you can iterate over it as many times as you like (if it is unchanged). Doing multiple loops over the String is better than multiple loops over the file.
    pbrockway2 likes this.

Similar Threads

  1. Replies: 37
    Last Post: 07-04-2011, 07:01 PM
  2. frequency of occurence of a letter in a string
    By manish007g in forum New To Java
    Replies: 4
    Last Post: 06-23-2011, 09:05 PM
  3. Counting occurence of a word in file
    By KAS in forum New To Java
    Replies: 15
    Last Post: 05-16-2011, 06:47 PM
  4. Searching the first occurence
    By The Hawk in forum New To Java
    Replies: 7
    Last Post: 11-29-2009, 12:36 PM
  5. count occurence of word in a line of text
    By sinyi88 in forum New To Java
    Replies: 19
    Last Post: 02-28-2009, 07:37 AM

Posting Permissions

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