1

文字列を入力し、使用されている各文字の数を出力する宿題があります。JOptionPane を使用していたときにロジックは機能していましたが、宿題は既に提出しています。ただし、JFrame JTextArea の入力と出力を使用するようにコードを「変換」しようとすると、出力に正しい文字数が表示されません。これは私の論理では非常に単純なものだと確信していますが、わかりません

出力は次のようになります。

ここに画像の説明を入力

ここにコードがあります

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;

public class Launcher extends JFrame
{

    // create panel components
    private static JTextArea txaUserInput;
    private static JTextArea txaResults;
    private static JButton btnSearch;

    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Final Answer");
        Border b = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY);
        txaUserInput = new JTextArea();
        txaUserInput.setPreferredSize(new Dimension(220, 70));
        txaUserInput.setBorder(b);
        txaUserInput.setLineWrap(true);
        txaResults = new JTextArea("Results");
        txaResults.setPreferredSize(new Dimension(200, 500));
        txaResults.setBorder(b);
        btnSearch = new JButton("Count Occurences of Each Letter");

        frame.setLayout(new FlowLayout());
        frame.add(txaUserInput);
        frame.add(btnSearch);
        frame.add(txaResults);
        createAndShowGUI();
        frame.setSize(300, 700);
        frame.setVisible(true);
    }

    private static void createAndShowGUI()
    {
        btnSearch.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                // create variables
                int[] counts = new int[26];
                int count = 0;

                String input = "";
                String output ="";

                for (short i = 0; i < (input).length(); i++)
                {
                    char temp = Character.toLowerCase((input).charAt(i));
                    if (temp >= 'a' && temp <= 'z')
                        counts[temp - 'a']++;
                }

                for (short i = 0; i < counts.length; i++)
                {
                    output += (char) ('a' + i) + ":\t " + counts[i] + "\n";
                }

                for (short i = 0; i < (input).length(); i++)
                {
                    if ((input).charAt(i) == 'a' || (input).charAt(i) == 'A')
                        count++;
                }

                txaResults.setText(output);

            }

        });
    }
}
4

3 に答える 3