Yahoo Answers is shutting down on 4 May 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

JAVA count specific letters and show it in output?

Please someone help me!!!

"ALL IS QUIET NOW, BUT WAIT!" must be inputted by the user and the output must show the the frequency of letters Q, A, E, and T. It should look like this    

OUTPUT:

Q = 1

A = 2

E = 1

T = 3

    public void createCharacterFinder() {

    characterFinder = new JPanel();

    characterFinder.setLayout(null);

    JLabel enterLabel = new JLabel ("Antipolo Campus");

    enterLabel.setBounds(100, 5, 260, 20);

    characterFinder.add(enterLabel);

    enterText = new JTextField();

    enterText.setBounds(10, 35, 270, 70);

    characterFinder.add(enterText);

    JButton search = new JButton("Enter");

    search.setBounds(50, 110, 200, 20);

    search.addActionListener(this);

    characterFinder.add(search);

    countText = new JTextField();

    countText.setBounds(10, 135, 270, 150);

    characterFinder.add(countText);

    }

    public void actionPerformed(ActionEvent e) {

    String st = enterText.getText();

    char searchedChar = enterText.getText().charAt(0);

    char [] charsToSearch = enterText.getText().toCharArray();

    count(searchedChar, st);

    }

    public int count (char c, String str) {

    int cnt = 0 ;

    for (int i = 0;; cnt++) {

    if ((i = str.indexOf(c, i)+1) == 0) break;

    }

    countText.setText(c+ " = "+cnt);

    return cnt;

    }

3 Answers

Relevance
  • 2 weeks ago

    Your count() method will work with a small change.  The .indexOf() method in String returns -1, not 0, if the character is not found.

    I'd write it this way:

        int count(char c, String str) {

            int result = 0;

            int i = str.indexOf(c); // 1st search with no start index

            while (i >= 0) {

                result += 1;

                i = str.indexOf(c, i+1); // Each new search begins after previous one

            }

            return result;

        }

  • 2 weeks ago

    Hi, Alfred.

    Your count method could work like this:

        public int count (char c, String str) {

            int cnt = 0;

            for (char ch: str.toCharArray()) {

                if (ch==c) cnt++;

            }

            return cnt;

        }

  • EddieJ
    Lv 7
    2 weeks ago

    characterFinder = new JPanel();

    would either have to be:

    JPanel characterFinder = new JPanel();

    or, somewhere in your program you'd need:

    JPanel characterFinder;

Still have questions? Get answers by asking now.