计算所有256个字符的出现次数(GUI / Arrays)

时间:2014-02-26 02:21:37

标签: java awt jfilechooser text-processing mixing

我需要帮助调整我的代码。我需要编写一个程序,在用户上传的txt文件中输出单个ascii字符的数量,但是我在尝试获取我计入“绘制的程序的GUI部分”中的数组时遇到了很多问题“屏幕上的数据。 我的输出看起来像我想要的,但我无法弄清楚如何让字符计数在那里

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import java.io.FileReader;      // both needed
import java.io.BufferedReader;
import java.io.IOException;


public class textreader extends Frame implements ActionListener
{
String dataFilePath = null;
String dataFileName = null;
int[] counter = new int[256];

String command = "";

public static void main(String[] args)
{
    Frame frame = new textreader();
    frame.setResizable(true);
    frame.setSize(1000,850);
    frame.setVisible(true);
}

 public textreader()
{
     setTitle("Text File Processing");

    // Menu Creation
     MenuBar mn = new MenuBar();
    setMenuBar(mn);

    // Create "File" and add it
    Menu fileMenu = new Menu("File");
     mn.add(fileMenu);

    // Create Menu Items, Add action Listener, Add to "File" Menu Group

    // Open file
    MenuItem miOpen = new MenuItem("Open");
    miOpen.addActionListener(this);
    fileMenu.add(miOpen);

    // Process file
    MenuItem miProcess = new MenuItem("Process");
    miProcess.addActionListener(this);
    fileMenu.add(miProcess);

    // Exit program
    MenuItem miExit = new MenuItem("Exit");
    miExit.addActionListener(this);
    fileMenu.add(miExit);

    // To Terminate
    WindowListener d = new WindowAdapter()
    {
        public void windowClosing(WindowEvent ev)
        {
            System.exit(0);
        }

        public void windowActivated(WindowEvent ev)
        {
            repaint();
        }

        public void windowStateChanged(WindowEvent ev)
        {
            repaint();
        }
    };

    ComponentListener k = new ComponentAdapter()
    {
        public void componentResized(ComponentEvent e) 
        {
            repaint();           
        }
    };

    // listener registry
    this.addWindowListener(d);
    this.addComponentListener(k);
}

public void actionPerformed (ActionEvent ev)
{
// which command was issued?
command = ev.getActionCommand();

// act          
if("Open".equals(command))
{
    dataFilePath = null;
    dataFileName = null;

      JFileChooser chooser = new JFileChooser();
      chooser.setDialogType(JFileChooser.OPEN_DIALOG );
      chooser.setDialogTitle("Open Data File");

      int returnVal = chooser.showOpenDialog(null);
      if( returnVal == JFileChooser.APPROVE_OPTION) 
        {
          dataFilePath = chooser.getSelectedFile().getPath();
          dataFileName = chooser.getSelectedFile().getName();
        }
    repaint();
}
else
    if("Process".equals(command))
    {
        try 
        {   
            // Initialize
            int[] aCount = new int[256];

            // "Instantiate" streams
            BufferedReader inputStream  = new BufferedReader(new FileReader(dataFilePath));

            // read the file line by line and count the characters read

            String line = null;
            char c = 0;
            int lineLength = 0;
            int charValue = 0;

            while ((line = inputStream.readLine()) != null)
            {
            // *********  process line
                for (int i = 0; i < line.length(); i++)
                {
                    char ch = line.charAt(i);

                    if (ch >= 0 && ch <= 255)
                    {
                        counter[(int)ch]++;
                    }
                    else
                    {    // silently ignore non-ASCII characters
                    }
                    // count newline at the end
                    counter['\n']++;
                    }
                }
        }

        catch(IOException ioe)
        {
            System.out.print("You want to run that by me again?"); 
        }

        repaint();
    }
else
    if("Exit".equals(command))
    {
        System.exit(0);
    }

}
//********************************************************
//called by repaint() to redraw the screen
//********************************************************

public void paint(Graphics g)
{               
if("Open".equals(command))
{
    // Acknowledge that file was opened
    if (dataFileName != null)
    {
        g.drawString("File --  "+dataFileName+"  -- was successfully opened", 400, 400);
    }
    else
    {
        g.drawString("NO File is Open", 400, 400);
    }

    return; 
}
else
if("Process".equals(command))
    {
        for(int i = 0; i < 256; i++)
        {
             int x = 100;
             int y = 100;

             g.drawString("Int", x, y);
             g.drawString("Char", x+50, y);
             g.drawString("Count", x+100, y);
             g.drawLine(100, y+15, x+120, y+15);

             y = y + 30;

             int line = 0;

            for(int j = 0; j < 256; j++)
            {
                 line++;
                 g.drawString(Integer.toString(j), x, y);
                g.drawString(Character.toString((char)j), x + 50, y);   // Converts the # to a char, then to a String

                // This part of the code adds a new column when    the flag reaches 43

                if(line == 45)
                 {
                    x = x + 150;
                     y = 100;
                    g.drawString("Int", x, y);
                    g.drawString("Char", x+50, y);
                    g.drawString("Count", x+100, y);
                    g.drawLine(100, y+15, x+120, y+15);
                    y = y + 15;
                    line = 0;
                    }
                y = y+15;
                }

        }
        return; 
    }

    }
}

1 个答案:

答案 0 :(得分:1)

您的charValue变量似乎打破了您的逻辑。你应该删除它。这就足够了:

for (int i=0; i<alphabetArray.length; i++)
    alphabetArray[i] = 0; // set initial values

while ((line = inputStream.readLine()) != null) {
    for(int i=0; i<line.length(); i++)
        alphabetArray[(int)line.charAt(i)]++; // use the ASCII value of the character as an index
}

您的字母计数器似乎也超出了范围。要么(1)使alphabetArray成为类的实例变量,要么(2)在超出范围之前显示其内容。我认为#1更可取。

我也会关注这一行:

System.out.println(c + "  : "+ char.alphabetArray[i]);

char是一种数据类型,其中不存在alphabetArray(此时技术上不存在,因为它已超出范围)。 c也未定义。利用ASCII值!但是,请小心打印不可打印的字符等。你的输出看起来很时髦。

System.out.println((char)i + "  : "+ alphabetArray[i]);

当然,你仍然需要以某种方式使alphabetArray可访问。