Search code examples
javaswinguser-interfaceuser-input

Count occurrence of characters in JTextArea


I have this project where I have to count each of the characters the user has inputted inside the JTextArea, output the letter and the number of times it occurred in the JTextArea. My code works in a way that it counts each characters in that the user inputted in the JTextArea, but what I needed to do is if the character is repeated, it will only show once, with its corresponding count. Can anyone help? Here is my code.

        btn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                            
            String text = textbox1.getText();
            int num[] = new int [MAX_CHAR];
            int size = text.length();
            
              for(int i = 0; i < size; i++ ) {
                num[text.charAt(z)]++;  
                            
                textbox6.append("'" + text.charAt(i) + "' -" + 
                               num[text.charAt(i)] + ", \n");   
              }
            }
       }

For example textbox1.setText("Here's an example") What my code does is to print every character in the JTextArea and then count how many of that character there is like this 'h' - 1, 'e' - 1, 'r' - 1, 'e' - 2, ''' - 1, 's' - 1, ' ' - 1, 'a' - 1, 'n' - 1, ' ' - 2, 'e' - 3, 'x' - 1, 'm' - 1, 'p' - 1, 'l' - 1, 'e' - 4

Output should only show the repeated characters once with its corresponding count as to how many of that character there is in the string. Like this 'h' - 1, 'e' - 4, 'r' - 1, ''' - 1, 's' - 1, ' ' - 2, 'a' - 2, 'n' - 1, 'x' - 1, 'm' - 1, 'p' - 1, 'l' - 1


Solution

  • You have to count first and then use another loop to print it.

    btn.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
                        
            String text = textbox1.getText();
            int num[] = new int [MAX_CHAR];
            int printed[] = new int [MAX_CHAR];
            int size = text.length();
            
            for(int i = 0; i < size; i++ ) {
                num[text.charAt(i)]++;
            }
            for(int i = 0; i < size; i++ ) {
                if (printed[text.charAt[i]] == 0) {
                    printed[text.charAt[i]] = 1;
                    textbox6.append("'" + text.charAt(i) + "' -" + 
                                    num[text.charAt(i)] + ", \n");
                }
            }
        }
    }
    
    

    Here printed array is used to keep track of which characters are already printed.