Number of occurrences of letter

Assignment Help Business Management
Reference no: EM131958505

File CountLetters.java contains a program that reads a word from the user and prints the number of occurrences of each letter in the word. Save it to your directory and study it, then compile and run it to see how it works. In reading the code, note that the word is converted to all upper case first, then each letter is translated to a number in the range 0..25 (by subtracting 'A') for use as an index. No test is done to ensure that the characters are in fact letters.

1. Run CountLetters and enter a phrase, that is, more than one word with spaces or other punctuation in between. It should throw an ArrayIndexOutOfBoundsException, because a non-letter will generate an index that is not between 0 and 25. It might be desirable to allow non-letter characters, but not count them. Of course, you could explicitly test the value of the character to see if it is between 'A' and 'Z'. However, an alternative is to go ahead and use the translated character as an index, and catch an ArrayIndexOutOfBoundsException if it occurs. Since you want don't want to go further when a non-letter occurs, the handler will be empty. Modify this method as follows:

§ Put the body of the first for loop in a try.

§ Add a catch that catches the exception, but don't go further with it.

Compile and run your program.

2. Now modify the body of the catch so that it prints a useful message (e.g., "Not a letter") followed by the exception. Compile and run the program. Although it's useful to print the exception for debugging, when you're trying to smoothly handle a condition that you don't consider erroneous you often don't want to. In your print statement, replace the exception with the character that created the out of bounds index. Run the program again; much nicer!

// ****************************************************************

// CountLetters.java

//

// Reads a words from the standard input and prints the number of

// occurrences of each letter in that word.

//

// ****************************************************************

import java.util.Scanner;

public class CountLetters

{

public static void main(String[] args)

{

int[] counts = new int[26];

Scanner scan = new Scanner(System.in);

//get word from user

System.out.print("Enter a single word (letters only, please): ");

String word = scan.nextLine();

//convert to all upper case

word = word.toUpperCase();

//count frequency of each letter in string

for (int i=0; i < word.length(); i++)

counts[word.charAt(i)-'A']++;

//print frequencies

System.out.println();

for (int i=0; i < counts.length; i++)

if (counts [i] != 0)

System.out.println((char)(i +'A') + ": " + counts[i]);

}

}

Reference no: EM131958505

Questions Cloud

How would you account for the transfer of tacit knowledge : Do we really even manage Knowledge or is this just a set of buzz words? ("I know it's true because I read it on the internet.")
Design changes that need to be taken to ensure the security : Design changes that need to be taken to ensure the security of your network. Ensure that your measures follow the multilayered approach to security
List tangible and intangible benefits and costs : Create the project charter and a tentative project schedule and Gantt chart using Microsoft project
Why should not petries staff build their own unique system : What do you think are the sources of the information Jim and his team collected? How do you think they collected all of that information?
Number of occurrences of letter : File CountLetters.java contains a program that reads a word from the user and prints the number of occurrences of each letter in the word.
Which of the fallacies is used in each given advertisement : Provide two different examples of advertising that show any of the above topics. Which of the above fallacies is used in each advertisement?
Difference between a class and an instance of a class : 1) What is the difference between a class and an instance of a class? Give an example. 2) What is information hiding, and how is it implemented in C++?
What other factors can contribute to alcohol abuse issues : List the factors that are inclusive of substance abuse. What other factors can contribute to alcohol abuse issues? Discuss potential treatment.
Used as discount rate in finite time annuity formula : How much would you be able to withdraw every year? Hint: the annual interest rate should be used as the discount rate in the finite time annuity formula.

Reviews

Write a Review

Business Management Questions & Answers

  Calculating the future value of a series of amounts

Calculating the Future Value of a Series of Amounts. Elaine Romberg prepares her own income tax return each year. A tax preparer would charge her $80 for this service. Over a period of 10 years, how much does Elaine gain from preparing her own tax re..

  Revenue models and potential strategic alliances

Bob wants you to consider each of the other revenue models and potential strategic alliances which might make sense for this site. Write a report of 200 words, summarised with recommendations?

  Suggestions for improving project quality

Describe three suggestions for improving project quality for IT-projects (or other types of projects if you are not in the IT industry) that were not made in Chapter 8 of the Schwalbe text.

  Presume you parking lot has two different consumers

Presume you parking lot has two different consumers who use it at two different times. Daily commuters use it during day time as well as sports fans use it at different times to park at sporting events

  Develop strategic recommendations to the board of directors

Perform competitor analysis. Develop strategic recommendations to board of directors including rationale. Discuss organization's current goals and objectives.

  Customer satisfaction - qualitative vs quantitativecustomer

customer satisfaction - qualitative vs. quantitativecustomer satisfaction is extremely important for the long-term goal

  Unregulated cortisol and stress hormone

What term is used in this article to describe the regulatory axis of the reproductive system? What is the principle regulatory hormone for this axis?

  Find a scholarly business research article

Using the University Library, find a scholarly business research article that uses qualitative data collection and analysis methods. Read the article all the way through before you post. Use this week's lecture to aid your analysis.

  Marketing is and does and comment as appropriate

Notice that many classmates are posting very different notions of what marketing is and does and comment as appropriate.

  Describe ethical culture in your organization

Provide a definition of what an ethical leader is. Give an example of an ethical leader and describe why this person fits the definition. Describe ethical culture in your organization. Describe how to create conversations about ethics.

  Different information systems beneficial

How is the use of EHRs throughout different information systems beneficial to a patient and the health care provider?

  How does enterprise resource planning affect feedback

All businesses confront specific and identifiable types of strategic challenges over time as they develop through stages.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd