JAVA count specific letters and show it in output?

2021-04-19 11:09 pm
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)

2021-04-20 12:04 am
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;
    }
2021-04-19 11:35 pm
characterFinder = new JPanel();

would either have to be:
JPanel characterFinder = new JPanel();

or, somewhere in your program you'd need:
JPanel characterFinder;
2021-04-20 2:36 am
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;
    }


收錄日期: 2021-04-26 16:09:08
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20210419150917AA7BAlA

檢視 Wayback Machine 備份