Write a one class stand-alone application called AvLetter that reads in a phrase
ID: 3620516 • Letter: W
Question
Write a one class stand-alone application called AvLetter that reads in a phrase from the keyboard, and then prints the "average" letter in the phrase.What do we mean by the average letter in a phrase? Surely, in the phrase "abcde" the average letter should be c -- the a and the e average to c, and do the b and the d. Similarly, in the phrase "az", the average should be (and is) m, which is half way between a and z.
Notice that a phrase can contain blanks, punctuation, digits, etc. -- you should skip these. Only letters matter for this problem. Also, you should convert the phrase to all lower case before you begin your analysis.
Here is how you should proceed: every letter has a "position" in the type char, and you can find that position by casting the letter as an int. So you should traverse the String (input phrase, all lower case) from beginning to end, and whenever you come to a letter, cast it as an int and add this cast value to an accumulator variable. Then, when you've finished processing the String, divide the accumulated values of the letter by the number of letters you've seen. This division should be an integer division so the result will be an int. Cast this value back to a char to get the sought-after average.
An Example
Suppose the entered string is
Hi Sy!
First this is converted to lower case. Then the string is examined, character by character, left to right. The blank and the ! are skipped. These are the int values of the letters:
h = 104
i = 105
s = 115
y = 121
These sum to 445. Dividing by 4 yields 111, and (char)111 is 'o'
And here is the interaction from the running program:
> run AvLetter
enter a phrase
Hi Sy! <the value typed>
average is: o
>
Tips
Use the nextLine() method from the Scanner class to read in a whole phrase
Casting between int and char was discussed in class lecture #6, and is also discussed in a movie in the text, section 4.1.
To test if a character c is a letter you can simply write Character.isLetter(c).
Be sure to watch the movie on looping and accumulation in section 4.5.
You will need two accumulation variables for this program: one to count the number of letters seen, and another to sum the int values of those letters. Use reasonable names for these, e.g., letterCount, sum. Do NOT simply use x and y.
Thanks
Explanation / Answer
This question was asked and answered here.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.