Results 1 to 18 of 18
Like Tree5Likes
  • 1 Post By Dark
  • 1 Post By JosAH
  • 1 Post By sunde887
  • 1 Post By Dark
  • 1 Post By Dark

Thread: Letter counter program. having trouble understanding it.

  1. #1
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default Letter counter program. having trouble understanding it.

    Hi, I am having trouble understanding this code from my book, it is a simple letter counter that takes in your sentence, then lists the capital letters and lowercase letters in it, including any non alphabetical characters. I have commented the code that I don't understand, any help greatly appreciated. Thank you. Derek


    Java Code:
    //********************************************************************
    //  LetterCount.java       Author: Lewis/Loftus
    //
    //  Demonstrates the relationship between arrays and strings.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class LetterCount
    {
       //-----------------------------------------------------------------
       //  Reads a sentence from the user and counts the number of
       //  uppercase and lowercase letters contained in it.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          final int NUMCHARS = 26;
    
          Scanner scan = new Scanner (System.in);
    
          int[] upper = new int[NUMCHARS];
          int[] lower = new int[NUMCHARS];
    
          char current;   // the current character being processed
          int other = 0;  // counter for non-alphabetics
    
          System.out.println ("Enter a sentence:");
          String line = scan.nextLine();
    
          //  Count the number of each letter occurence
          for (int ch = 0; ch < line.length(); ch++)
          {
             current = line.charAt(ch);
             if (current >= 'A' && current <= 'Z')
                upper[current-'A']++; [COLOR="green"]//I DON'T UNDERSTAND WHAT CURRENT - A DOES. CAN YOU SUBTRACT FROM LETTERS? AND THE ++?[/COLOR]
             else
                if (current >= 'a' && current <= 'z')
                   lower[current-'a']++;[COLOR="green"]//I DON'T UNDERSTAND THIS EITHER, AND THE ++[/COLOR]
                else
                   other++;
          }
    
          //  Print the results
          System.out.println ();
          for (int letter=0; letter < upper.length; letter++)
          {
             System.out.print ( (char) (letter + 'A') );[COLOR="green"]//DONT UNDERSTAND WHAT (CHAR) (LETTER + A) IS DOING[/COLOR]
             System.out.print (": " + upper[letter]);
             System.out.print ("\t\t" + (char) (letter + 'a') );
             System.out.println (": " + lower[letter]);
          }
    
          System.out.println ();
          System.out.println ("Non-alphabetic characters: " + other);
       }
    }

  2. #2
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    Ok what are you asking us to do?

    EDIT: Didn't realize that your questions were comments in the code.
    silverglade likes this.
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,532
    Blog Entries
    7
    Rep Power
    20

    Default

    Characters are internally (small) numbers, what we see as an 'A' internally is 65. There are 65000 of those numbers (characters). Symbolically we can conveniently write them as e.g. 'A' and we wrote 65 actually. So any number - 'A' is understood as that number - 65. The type of those numbers is 'char' to distinguish them from ordinary ints.

    kind regards,

    Jos
    silverglade likes this.
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    Please explain the commented code, I played with it, and still can't figure out what it means. I know how it works but I don't understand the syntax of it. here below, please.


    Java Code:
     upper[current-'A']++; [COLOR="darkgreen"]//I DON'T UNDERSTAND WHAT CURRENT - A DOES. CAN YOU SUBTRACT FROM LETTERS? AND THE ++?[/COLOR]
             else
                if (current >= 'a' && current <= 'z')
                   lower[current-'a']++;[COLOR="darkgreen"]//I DON'T UNDERSTAND THIS EITHER, AND THE ++[/COLOR]
                else
                   other++;
          }
    
          //  Print the results
          System.out.println ();
          for (int letter=0; letter < upper.length; letter++)
          {
             System.out.print ( (char) (letter + 'A') );[COLOR="darkgreen"]//DONT UNDERSTAND WHAT (CHAR) (LETTER + A) IS DOING[/COLOR]

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    This is using ASCII values to change the characters. So you have an array which can hold 26 values(a-z), and another for the capitals(A-Z). The letters a-z (lower and upper case) are not represented by 0 in ASCII code. To test this, try casting a char to an int and printing it. Off the top of my head I believe lower case a starts at 65, and upper case starts at 97, verify this by googling ASCII charts.

    If you want to see which number lowercase a is in terms of 0-25, you can subtract the character 'a' from it. 'a'-'a' is 0, 'b'-'a' is 1 ... 'z'-'a' is 25.

    The other part of code, printing is similar, if you are looping through lower case letters, adding 'a' to the letter variable and casting it to a char will make it print 'a'.

    If you have any confusions still please let me know.
    silverglade likes this.

  6. #6
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    Thank you very much Jos, once again. :) I will relook at the code now thank you. And thank you once again Sunde887!!! nice to see you are up and awake at the same time as me. hehe. Derek

  7. #7
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    On top of what JosAH said, the ++ is an increment. All its doing is increasing the represented number by one.
    silverglade likes this.
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

  8. #8
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    Ok I have tried HARD to get it, but I still don't totally, but I do understand more than i did. Ok I have commented the questions again if you can help again please. Thank you.


    Java Code:
    //********************************************************************
    //  LetterCount.java       Author: Lewis/Loftus
    //
    //  Demonstrates the relationship between arrays and strings.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class LetterCount
    {
       //-----------------------------------------------------------------
       //  Reads a sentence from the user and counts the number of
       //  uppercase and lowercase letters contained in it.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          final int NUMCHARS = 26;
    
          Scanner scan = new Scanner (System.in);
    
          int[] upper = new int[NUMCHARS];
          int[] lower = new int[NUMCHARS];
    
          char current;   // the current character being processed
          int other = 0;  // counter for non-alphabetics
    
          System.out.println ("Enter a sentence:");
          String line = scan.nextLine();
    
          //  Count the number of each letter occurence
          for (int ch = 0; ch < line.length(); ch++)
          {
             current = line.charAt(ch);[COLOR="darkgreen"] //get character from user's line and hold it in "current" variable[/COLOR]
             if (current >= 'A' && current <= 'Z')[COLOR="darkgreen"]//if is within the uppercase alphabet[/COLOR]
                upper[current-'A']++;[COLOR="darkgreen"] //point to lets say "E" - A = 4++ which is 5?? does that accomplish anything?[/COLOR]
             else
                if (current >= 'a' && current <= 'z')[COLOR="darkgreen"]// if current char is within the lowercase alphabet..[/COLOR]
                   lower[current-'a']++;
                else
                   other++;
          }
    
          //  Print the results
          System.out.println ();
          for (int letter=0; letter < upper.length; letter++)[COLOR="darkgreen"] //loop through the whole upper array[/COLOR]
          {
             System.out.print ( (char) (letter + 'A') );[COLOR="darkgreen"]//AWESOME SUNDE887!! OK, IF LETTER==0,PRINT A, IF LETTER==1, PRINT B, IS THAT CORRECT? does. when I run it it prints out A:0, B:0, etc.[/COLOR]
             System.out.print (": " + upper[letter]);[COLOR="darkgreen"]// I DONT KNOW HOW THIS OUTPUTS THE NUM OF LETTERS IN AN INDEX[/COLOR]
             System.out.print ("\t\t" + (char) (letter + 'a') );
             System.out.println (": " + lower[letter]); 
          }
    
          System.out.println ();
          System.out.println ("Non-alphabetic characters: " + other);
       }
    }
    Last edited by silverglade; 05-21-2011 at 10:58 AM.

  9. #9
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    Monkeys have that speed?
    silverglade likes this.
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

  10. #10
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    haha ya when I have coffee my brain is even faster than the monkey's. please see my latest post above, I understand more, but still not totally. thank you. Derek ( I don't drink coffee though)
    Last edited by silverglade; 05-21-2011 at 10:22 AM.

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Unfortunately my phone Won't allow me to scroll through all the code, so you may have to ask other questions outside of the code if I don't address them.

    In the lines with the increment operator, notice you are not simple incrementing a random number, you are incrementing a number being indexed. You are indexing based on a character, so if you enter the letter 'a' and 'c', the array will increment slot 0 and 2 of the array, those two slots will now contain the number 1, since the input contained one a and one c.

    The other part has a loop with the letter value starting at zero, so for the first iteration of the loop, it will output 'A', because 0 + 'A' == 'A' when Castro a char. The second iteration will be 'B', likewise 1 + 'A' == 'B' and so on till letter== 25, 'A' + 25 == 'Z'

  12. #12
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

  13. #13
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    thank you Sunde887, I am analyzing your reply now. thank you! Derek

  14. #14
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    Ok, other than this 5 page code example previously in my book which I just ignored rather than messing with it, this was the hardest code to understand in my book, and it is page 360 only out of 715 pages. LOL. After stretching my brain , and painfully forging new pathways, I have included my comments to explain the code which "I think" are correct, if anyone was curious. Thank you everyone and Sunde887 again!:D

    Here it is!

    Java Code:
    //********************************************************************
    //  LetterCount.java       Author: Lewis/Loftus
    //
    //  Demonstrates the relationship between arrays and strings.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class LetterCount
    {
       //-----------------------------------------------------------------
       //  Reads a sentence from the user and counts the number of
       //  uppercase and lowercase letters contained in it.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          final int NUMCHARS = 26;
    
          Scanner scan = new Scanner (System.in);
    
          int[] upper = new int[NUMCHARS];
          int[] lower = new int[NUMCHARS];
    
          char current;   // the current character being processed
          int other = 0;  // counter for non-alphabetics
    
          System.out.println ("Enter a sentence:");
          String line = scan.nextLine();
    
          //  Count the number of each letter occurence
          for (int ch = 0; ch < line.length(); ch++)
          {
             current = line.charAt(ch);
             if (current >= 'A' && current <= 'Z')
                upper[current-'A']++;[COLOR="darkgreen"]// if "current==A, then A-A=0, so add 1 to index[0] which represents how many A's there are[/COLOR]
             else
                if (current >= 'a' && current <= 'z')
                   lower[current-'a']++;[COLOR="darkgreen"]//do the same for lower case.
                else[/COLOR]
                   other++;
          }
    
          //  Print the results
          System.out.println ();
          for (int letter=0; letter < upper.length; letter++)
          {
             System.out.print ( (char) (letter + 'A') );[COLOR="darkgreen"]//if letter==0, 0+A, print A, if 1+A print B[/COLOR]
             System.out.print (": " + upper[letter]);[COLOR="darkgreen"]// outputs contents of [index letter] array, the contents of which we set in the previous FOR block, so upper[0]==3, if your input string was "AAA".[/COLOR]
             System.out.print ("\t\t" + (char) (letter + 'a') );
             System.out.println (": " + lower[letter]);
          }
    
          System.out.println ();
          System.out.println ("Non-alphabetic characters: " + other);
       }
    }
    I hope this is correct, I don't want to confuse anyone. thanks. Derek

  15. #15
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I can't see it all, due to the problem with my phone, as mentioned above. It looks like you understand it now though. What page was the 5 page snippet on?

    Also, have you just been reading this book lately? Or some of the others you've gotten as well?

  16. #16
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    Ok Sunde887, I have only been reading this book "Java Software Solutions" which is where these codes are coming from. After I finish that, I am going back to "Head First Java" to finish that, then the big enchilada is going to be to read "Thinking In Java", then I might go to "effective java" after that. At least that is my tentative plan. Also the 5 page code newbie beast is on page 328, it is the "Pig Latin" translator, and it seems pretty sophisticated for a newbie. I would have NEVER been able to come up with that, or the letter case counter. These little apps are actually pretty complicated for a newbie. I plan on going through this book several times over and over, rereading it, and each time it will be forming a deeper and deeper groove into my mind, until on the last reading, I am just flipping through pages as if I were reading English. I will probably be asking questions on this forum for the rest of my programming life. LOL. Thanks again Sunde887, Derek

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You are welcome. I have actually just started reading effective java, it's a great book but is definitely more advanced then head first java and software solutions.

    Glad to hear you are enjoying the book. Scanning software solutions for the exercises I really liked what the recursion chapter offers.

  18. #18
    silverglade is offline Senior Member
    Join Date
    Feb 2009
    Posts
    182
    Rep Power
    6

    Default

    Yes I thought I would save Effective Java for last. I like "Java Software Solutions " a lot. It is the best programming book I have ever read. A textbook for CS 1 students, and textbooks usually are harder for me. I just figured out the meaning and functions of a 4 page program. WOW. Not too hard it was pretty simple, no tricky algorithms or anything, just nice newbie code. I have a question about it which I am going to post on a new post the question is pretty easy, Basically there is a call to print 2 different String toString methods, and I don't know why, because it looks like only one is used. I tried to write more code but the book exercises keeps putting in advanced things needed, so I figured I would read the whole book now and go back and do the exercises with the full knowledge.
    EDIT: To anyone reading this here are my newbie suggestions. Use a highlighter to mark important parts, and use a pen to follow the program flow and mark it down, your notes will look like plans to an atomic bomb soon, but it is worth it later.
    Last edited by silverglade; 05-21-2011 at 01:09 PM.

Similar Threads

  1. Having trouble understanding how to use Hash Tables
    By theBurgh22 in forum Advanced Java
    Replies: 1
    Last Post: 03-04-2011, 11:19 PM
  2. trouble understanding code help
    By yasmin k in forum New To Java
    Replies: 4
    Last Post: 11-16-2009, 09:46 PM
  3. Having trouble understanding Class Graphic
    By Bernard Robitaille in forum JCreator
    Replies: 1
    Last Post: 04-18-2009, 02:55 AM
  4. I have trouble understanding this program!
    By PureAwesomeness in forum New To Java
    Replies: 1
    Last Post: 03-16-2009, 05:34 AM
  5. [SOLVED] Trouble understanding or expressions
    By hungdukie in forum New To Java
    Replies: 1
    Last Post: 11-23-2008, 01:24 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
  •