Jump to content

[Java] Frequency Analysis in Java


WarFox
 Share

Recommended Posts

My java implementation of a program that does frequency analysis of documents.

 

CharList.java

Spoiler

import java.lang.*;
import java.util.ArrayList;

public class CharList {

	private char[] allChar = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
	       'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
		'v', 'w', 'x', 'y', 'z'};
	private ArrayList<Node> list;
	private long totalLetters;

	public CharList () {
		list = new ArrayList<>();
		for (char c : allChar) {
			list.add(new Node(c));
		}
		totalLetters = 0;
	}

	public void findAndIncrement (char c) {
		for (Node n : list) {
			if (n.getCharacter() == c) {
				n.increaseCount();
				totalLetters++;
			}
		}
	}

	public long getTotalLetters () {
		return totalLetters;
	}

	public double percentage (long letterCount) {
		return (double) letterCount / totalLetters;
	}

	public ArrayList<Node> getList () {
		return list;
	}

	public void printResults () {
		System.out.println("Results");
		System.out.println("---------------");
		for (Node n : list) {
			System.out.println(n.getCharacter() + ": " + n.getCount() + " " + percentage(n.getCount()) + "%");
		}
	}

    public String results () {
        String s = "Results\n" + "---------------\n";
        for (Node n : list) {
            s = s + n.getCharacter() + ": " + n.getCount() + "     " + percentage(n.getCount()) + "%" + "\n";
        }
        return s;
    }

	protected class Node {
		 /*
		  * Instance Variables
		  */
		private char character;
		private long count;
		
		public Node (char pCharacter) {
			character = pCharacter;
			count = 0;
		}

		public char getCharacter () {
		       return character;
		}

		public long getCount () {
			return count;	
		}

		public void increaseCount() {
			count++;
		}
	}
}

 

Analyze.java

Spoiler

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;

public class Analyze {
	
	/*
	 * Instance Variables
	 */

	private CharList charList;
	private Scanner in;

	/*
	 * Constructors
	 */
	public Analyze (String pFileName) throws FileNotFoundException {
		charList = new CharList();
		in = new Scanner (new File(pFileName));
	}

	public boolean analyzeFile () throws FileNotFoundException {
		while (in.hasNextLine()) {
			String line = in.nextLine();
			line.toLowerCase();
			line.trim();
			char[] letters = line.toCharArray();
			for (char c : letters) {
				charList.findAndIncrement(c);
			}
		}
		in.close();
		return true;
	}

	public void getResults () {
		charList.printResults();
	}

	public String passResults () {
		return charList.results();
	}

}

 

Main.java

Spoiler


import java.lang.*;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class Main {

    public static void main (String[] args) throws FileNotFoundException {
        Main main = new Main();
        if (args.length == 0) {
		main.run();
	} else if (args.length != 0) {
		main.guiRun();
	}
    }

    public void run () throws FileNotFoundException {
        String fileName;
        Scanner in = new Scanner(System.in);
        System.out.println("Frequency Analysis \n" +
                "-----------------------------\n" +
                "Enter a file name: ");
        fileName = in.nextLine();

        Analyze analyze = new Analyze(fileName);
        boolean sucessful = analyze.analyzeFile();
        if (sucessful) {
            analyze.getResults();
        } else {
            System.out.println("Error occured!");
            System.exit(-1);
        }
    }

	public void guiRun() {
		View view = new View();
	}

}

 

View.java

Spoiler

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.filechooser.FileSystemView;
import javax.swing.JFileChooser;
import java.io.FileNotFoundException;
import javax.swing.JOptionPane;

public class View extends JFrame implements ActionListener {

	private JButton submitButton;
	private JTextField fileTextField;
	private JButton selectFileButton;

	public View () {
		
		JPanel centerPanel = new JPanel (new BorderLayout());

		fileTextField = new JTextField();
		centerPanel.add(fileTextField, BorderLayout.CENTER);
	
		selectFileButton = new JButton("Select File");
		centerPanel.add(selectFileButton, BorderLayout.EAST);
		selectFileButton.addActionListener(this);

		submitButton = new JButton("Submit for Analysis");
		submitButton.addActionListener(this);
		centerPanel.add(submitButton, BorderLayout.SOUTH);


		JLabel title = new JLabel("FrequencyAnalysis4Doc");
	
		JPanel mainPanel = new JPanel(new BorderLayout());
		mainPanel.add(title, BorderLayout.NORTH);
		mainPanel.add(centerPanel, BorderLayout.CENTER);

		add(mainPanel);
		setVisible(true);
		setSize(500,100);
		setDefaultLookAndFeelDecorated(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed (ActionEvent e) {
		String buttonPressed = e.getActionCommand();
		if (buttonPressed.equals("Submit for Analysis")) {
			String fileName = fileTextField.getText();
			try {
				analyze(fileName);
			} catch (FileNotFoundException ex) {
				System.err.println("Error");
				System.exit(-1);
			}
		} else if (buttonPressed.equals("Select File")) {
			String file = selectFile();
			fileTextField.setText(file);
		}
	}

	private String selectFile() {
		JFileChooser fileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
		fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		int x = fileChooser.showOpenDialog(null);
		if (x == JFileChooser.APPROVE_OPTION) {
			return fileChooser.getSelectedFile().getAbsolutePath();
		} else {
			return null;
		}
	}

	public void analyze (String pFileName) throws FileNotFoundException {
		Analyze analyze = new Analyze(pFileName);
		boolean successful = analyze.analyzeFile();
		if (successful) {
			String results = analyze.passResults();
			JOptionPane r = new JOptionPane();
			r.showMessageDialog(this, results);
		} else {
			// error code
		}
	}

}

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...