Category Archives: Software Development

The Daily WTF

“The Daily WTF” (TDWTF) website is one that most people I know probably wouldn’t want to read on a daily basis, but I follow it with the help of an RSS feed. However, there are two stories on the TDWTF that I have to share, because you don’t need to be techy or geek to understand them, and they are fab!

The Proven Fix – I like this because it goes to show that actually testing something is 110% better than working through some intelectual process that suggests it might work!

Lacking Knowledge Essentials – Just when you think a company is so bad they will go out of business, they work with another business who makes them look organised! lol fantastic!

Subversion

Subversion is used for version control and, having recently set up a subversion repository, I wanted to share the experience. Previously my experience of versioning was SCCS and CVS, both of these systems do the job, but Subversion is very easy to use and setup. Over the last few months I have used it extensively and become very knowledgeable about it. I would recommend Subversion to any one needing version control, I use it for source files, but it would be equally good for any thing else, it handles binary and text files so there is no limit.

Here are some links should you want to find out more;

Subversion website – subversion.tigris.org
Subversion forums – www.svnforum.org

M255 Java Calculator

M255 Java Calculator

Having completed the Open University course M255 I decided I wanted to put my new found knowledge to use. I needed a project, and wanted to learn about how user interfaces are programmed in Java.

A Calculator seemed like a good project, but I set myself a few restrictions, they were;

  • Not allowed to use an ‘Integrated Development Environment’, I used the VI text editor instead.
  • Use compiler (javac) and Java Virtual Machine (java) to run it from the command line.
  • Not allowed to look at how other people had programmed a calculator
  • The only source of help was my knowledge of Java from M255, and, The Java Tutorials at the Sun website.

One of the reasons for putting the details of the project on the web was to show others what can be achieved after completing M255, and to welcome feedback from people, including experienced developers.

Source and Design

This project has been split into phases to make development more manageable within the limited time I have. Initialy I wanted to create a user interface that responded to all the events I needed and then make it work like a calculator. What surprised me was that it only took an hour and a half to create the user interface, being that I am no expert means I have probably not implemented it as well as I could have, but thats why ive signed up for M257.

Version Description Classes
v1.0
29th October 2006
Original version with basic calculator features Calculator
Calculation

Instructions

Future enhancements

As anyone working in software development knows, programs always evolve, and the Calculator is no different, I see the code/implementation changing as I receive comments from more experienced Java developers, and to add the following;

  • Convert into an Applet so people can see the Calculator on the web without having to download it and run it locally.
  • Add support for keyboard use, at present this is purely mouse driven.
  • Nested brackets
  • Improve the layout of the interface, it could look better.
  • Add other scientific functions, maybe even graphs as I get really adventurous.
  • … and more as either I think of them or people suggest them.

Warning!

As I am no expert on Java or Java user interfaces I obviously have no idea if there is a better way of achieving what I want, or for that matter if I have committed any sins in the code I have created; however, I hope this project evolves and can become a case study tracing the evolution of the calculator from the original source (v1.0) through it’s evolution into a more show case calculator program.

This is a purely educational project; I don’t see this being of any real use to any one other than to learn from.

Java: Calculator Instructions

Preperation

Should you not have the Java Virtual Machine (JVM) you can find it at java.sun.com, this is used to run Java programs. There are several ways you can run the Calculator, the way I have been running it is to place both class files in a directory, compile them both and then run the Calculator class, I used cygwin but a DOS prompt or any other shell should also be ok.

You can use an Integration Development Environment (IDE) to run the Calculator, instead of the command line; however, if your not using an IDE you might find the following usefull.

Compiling and running using a shell

Once you have your shell/DOS prompt you will want to create a suitably named directory, and then place both class files in it. The following shows where you should be in the directory structure and what files you should see in there.

$ pwd
/home/user/java/Calculator

user@user ~/java/Calculator
$ ls
Calculation.java  Calculator.java

Then from within the directory where the class files are, compile the class files using javac as follows.

$ javac Calculator.java

user@user ~/java/Calculator
$ javac Calculation.java

Once compiled you should see a few extra files, these will have a .class file extension, and they contain the bytecode which JVM will uses to execute, in this case resulting in the Calculator running and the user interface being displayed.

user@user ~/java/Calculator
$ ls
Calculation.class  Calculator$1.class  Calculator.java
Calculation.java   Calculator.class

Now you are ready to run the Calculator using the following command;

user@user ~/java/Calculator
$ java -classpath . Calculator

Assuming you have done everything correctly you should see something similar to the following;

Java: Calculation Class

Calculation Class

Description

Provides a mechanism to hold value of previous calculations, and then make new calculations with this value.

The way this class works is to hold value representing the current value of the calculator and a value repesenting the next operation (addition, multiplication etc) that needs to take place. Subsequent calls to public double calculate( double newValue, char newOperation ) result in the current calculator value being adjusted and the next operation value being replaced with the next new one.

Source

[css]
/*
 * Calculation
 *
 * This class receives numbers and operators and performs running calculations
 * Includes methods for accessing the state of the receiver
 *
 * Russell Smithers - 28th October 2006
 *
 */

import java.util.*;

public class Calculation
{

    private double currentValue; // Current value of calculation
    private char nextOperation;  // Operation to carry out when next value received

    /**
     * Constructor
     */
    public Calculation()
    {
        this.currentValue = 0.0; this.nextOperation = '+';
    }

    /**
     * Calculates and sets a new value for the receiver based upon the receivers next oparator
     * its current value, and the value passed in, and then sets the next operation of the
     * receiver to the operation passed in.
     */
    public double calculate( double newValue, char newOperation )
    {
        double result;
        char op = this.getOperation();
        result = Calculation.calculate(this.getValue(), this.getOperation(), newValue);
        this.setValue( result );
        this.setOperation( newOperation );
        return result;
    }

    /**
     * Performs a calculation on an (number operator number)
     */
    public static double calculate( double leftSide, char howCalc, double rightSide )
    {
        double result=0.0;
        try
        {
            //result = leftSide + howCalc + rightSide;
            switch(howCalc)
            {
                case '+': result = leftSide + rightSide; break;
                case '-': result = leftSide - rightSide; break;
                case '*': result = leftSide * rightSide; break;
                case '/': result = leftSide / rightSide; break;
            }

        }
        catch(Exception anError)
        {
            System.out.println("Calculation.calculate() - " + leftSide + " " + howCalc + rightSide + ": " +anError);
        }
        System.out.println("calculate(double, char, double) " + result );
        return result;
    }

    /**
     * Changes the receiver to be the result of a calculation between itself and newCalc
     * The calculation is the same as; public void calculate( double newValue, char newOperation )
     */
    public double calculate( Calculation newCalc )
    {
        return this.calculate( newCalc.getValue(), newCalc.getOperation() );
    }

    /**
     * Returns true if the operation to be tested is one that this Calculation can deal with
     */
    public static boolean operationValid(char testOperation)
    {
        boolean valid;
        switch(testOperation)
        {
            case '+':
            case '-':
            case '*':
            case '/':
            case '=':
                valid=true;
                break;
            default: valid=false;
        }
        return valid;
    }

    /**
     * Sets the current value of the receiver
     */
    public void setValue(double newValue)
    { this.currentValue = newValue; }

    /**
     * Sets the nextOperation of the receiver
     * returns true if succesfull
     */
    public boolean setOperation( char newOperation )
    {
        if ( Calculation.operationValid( newOperation ) )
        {
            // If operation is equals set it to plus
            this.nextOperation = ( newOperation == '=' ? '+' : newOperation);
            return true;
        }
        return false;
    }

    /**
     * Returns the current value of the receiver
     */
    public double getValue()   { return this.currentValue; }

    /**
     * Returns the nextOperation of the receiver
     */
    public char getOperation() { return this.nextOperation; }

    /**
     * Returns a string representation of the receiver
     */
    public String toString()
    {
        return "The current value is " + currentValue + " and the next operation to be performed is " + nextOperation;
    }

}
[/css]

Java: Calculator Class

Calculator Class

Description

Provides the graphical user interface of the calculator. Looking at the code you will see the method;

public void actionPerformed(ActionEvent e)

which is the central hub of the Calculator, it is the point at which the user actions (events) are turned into sequences of actions that result in calculations being performed, and their result being shown to the user.

Source

[css]
/*
* Calculator
*
* Russell Smithers
* 26 October 2006
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator implements ActionListener
{
// Display area references
public JPanel mainPanel, selectPanel, displayPanel, actionPanel, memoryPanel;
private JLabel displayScreen;

// Calculation references and variables
Calculation currentCalc;
StringBuilder screenValue;
double value;
char valueInput;

/**
* Create a GUI Calculator – sets up swing with relevant controls
*/
public Calculator()
{
// Main panel that holds all controls
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(0,2));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

// Screen areas
this.displayPanel = this.addPanel(“Result”,0,0);
this.memoryPanel = this.addPanel(“Memory”,0,1);
this.selectPanel = this.addPanel(“Keypad”,0,3);
this.actionPanel = this.addPanel(“Operations”,0,1);

// Number buttons
for (int button=9; button>=0; button–)
{ this.addButton(selectPanel, “” + button); }
this.addButton(selectPanel, “.”);
this.addButton(selectPanel, “Clr”);

// Operation buttons
this.addButton(actionPanel, “+”);
this.addButton(actionPanel, “-“);
this.addButton(actionPanel, “/”);
this.addButton(actionPanel, “*”);
this.addButton(actionPanel, “=”);

// Output area
displayScreen = new JLabel();
this.displayPanel.add( displayScreen );
screenValue = new StringBuilder();

currentCalc = new Calculation();
}

/**
* Event handler which handles all input
*/
public void actionPerformed(ActionEvent e)
{
// System.out.println(“Button pressed: ” + e.getActionCommand() );
String valueOrig = e.getActionCommand();
this.valueInput = valueOrig.charAt(0);

if ( Calculation.operationValid(valueInput) )
{
try
{
this.value = Double.valueOf(screenValue.toString()).doubleValue();
}
catch(Exception anError)
{
this.value = 0.0;
}
currentCalc.calculate( this.value, valueInput);
this.updateDisplay();
}
else
{
if ( Character.isDigit(this.valueInput) || this.valueInput == ‘.’)
{
screenValue.append( this.valueInput );
this.displayScreen.setText( screenValue.toString() );
}
else
{
switch(this.valueInput)
{
case ‘C’: currentCalc.setValue(0.0);
}
this.updateDisplay();
}
}

}

/**
* Set calculator value
*/
public void updateDisplay()
{
this.displayScreen.setText( Double.toString(currentCalc.getValue()) );
this.screenValue = new StringBuilder();
}

/**
* Add a button with an ActionListener and then add it to a panel
*/
private void addButton(JPanel p, String value)
{
JButton tempButton = new JButton(value);
tempButton.addActionListener(this);
p.add(tempButton);
}

/**
* Adds a new panel the main container panel and sets default decoration
*/
private JPanel addPanel(String title, int x, int y)
{
JPanel tempPanel = new JPanel();

// Set GridLayout is we have relevant values to use on
if ( (x > 0) || (y >0) )
{ tempPanel.setLayout(new GridLayout(x,y)); }

// Set the panel decoration
tempPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(title), BorderFactory.createEmptyBorder(5,5,5,5)));

// Add ths panel to the main one
this.mainPanel.add(tempPanel);

return tempPanel;
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI()
{
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

Calculator calcy = new Calculator();

//Create and set up the window.
JFrame calculatorFrame = new JFrame(“Calculator v1.0 (rsmithers.net)”);
calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculatorFrame.setContentPane(calcy.mainPanel);

//Display the window.
calculatorFrame.pack();
calculatorFrame.setVisible(true);
}

/**
* Entry point for Calculator program
*/
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application’s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
[/css]

Standard Deviation – New Program

Introduction

This is a Standard Deviation calculator, written in C# .NET, it shows the workings out. Obviously Excel will calculate standard deviation if you just need a final figure.

Screen shot of the Standard Deviation Program Written in C# .NET

Purpose 

This application is aimed at those who want to understand how Standard Deviation is worked out, and can be useful in checking their calculations. You may find the following explanation useful; http://www.gcseguide.co.uk/standard_deviation.htm.

Quick Start Instructions

To use this application simple enter your figures into the 1st column on the grid, as each number is entered the standard deviation is recalculated. You can also use the import or past (Edit>Past) options to retrieve figures without having to enter them by hand.

Installation 

Please visit standard deviation release area to install onto your computer, or run it from the web.