Developing a Mini Calculator Part-3

Hello, this is third part of Developing a Mini Calculator. Today’s topic will cover Input Service and Output service module. Please read Developing a Mini Calculator Part-2 for understanding about Calculation logic.

Input Service

Like I said in the first section, input service is responsible for two things and they are accepting right input and preventing user from entering an input that may cause application behavior inconsistent. Input service alone can take some decisions for preventing user inputs. But sometimes it is not possible and that decision making require application state.

Consider an example scenario “user pressing period or dot key”. I will explain how the decision making works

How input service alone take decisions?

  • When application start input service will unlock period key
  • If user press period key input service will lock the period key
  • When user press period key it will send a message to core module saying user pressed period key

How input service take decision with the help of core module

  • When user press backspace key after pressing period key, input service will send a message to core module. Core module will understand that user pressed backspace key and so do a state change and send back a message to input service. So by identifying this message from core, input service can enable or unlock the period key.

Output Service

Output service is responsible for managing the screen and doing this by showing allowed application state to the screen. Output service will do this with the help of core, because core manage the application state.

Consider an example scenario “user entering number ‘6.’ and press backspace key to delete the dot character”

Hitting backspace key will initiate a message from input service to core. Core do the necessary state change and send a message to input service. After this core will send a message to output service  to delete the dot character from screen.


  • Once messages are defined we can use it uniquely across all modules
  • Each module can be managed independently
  • Since communication across modules are achieved using messages, so maintenance is easy


Here ends the third session on mini calculator development. Hope you liked it ūüôā . In next topic I will explain about core module and communication between different modules using messages ūüôā


Creating Slide Show using Java

Today i was doing some search in my personal computer prior to formatting the hard disk and to take backup of important files and I came across a small java source code file. I wrote this code during my collage days and did it as part of the technical exhibition conducted by my college. As part of it I got a chance to prepare some presentation on game development basics and created some slides. All I wanted was to run this slides (images) in an equal interval of time, so it will run continuously in circular fashion without any user intervention. The program will load the predefined images using the file name and display it for three seconds and move it to next image. After reaching the the last image, it will start again from the first image. I would like to share the code here ūüôā

Source Code

import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

class JavaSlider extends JPanel implements Runnable {
	private Thread sliderThread;
	private boolean active;
	private JFrame parent;
	public JavaSlider(JFrame parent) {
		sliderThread = new Thread(this);
		active = false;
		println("Panel created...");
		this.parent = parent;
	public void setActive(boolean status) {
		println("Thread activated/deactivated...");
		active = true;
	public Thread getThread() {
		return sliderThread;
	public void start() {
		println("Thread started...");
	public void run() {
		int counter = 1;
		String name = "";
		while (active) {
			try {
				name = "slide" + counter + ".png";
				println("Loading file " + name + "...");
				BufferedImage image =;
				println("Loaded file " + name + "...");
				parent.setSize(image.getWidth() + 4, image.getHeight() + 32);
				getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);
				if (++counter > 23) {
					println("Reseting counter...");
					counter = 1;
			} catch (IOException | InterruptedException ex) {
	public static void main(String[] args) throws InterruptedException {
		JFrame frame = new JFrame("Java Slider");
		JavaSlider panel = new JavaSlider(frame);
		frame.setSize(960, 720);
		frame.setLocation(0, 0);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
	public static void println(String message) {

Game Development Season 1

Hello, today I am going to show you how to develop a computer game where character run continuously along a straight road collecting points and avoiding obstacles.

What are the things required while developing this type of game?

Character development

The game have a main character. We have to give a proper behavior.

  • Character can jump left or right, jump over the obstacles, slide under obstacles.
  • Character will die when hit the obstacles and so game will end.
  • Character can collect points from the road by hitting them.


World is where we have everything in picture. The road, points, obstacles and main character. The obstacles are vehicles and hurdles. The main character have to jump over vehicles and slide under the hurdles. Or simply jump left or right. The road will have three lines. Where vehicles move towards main character.

If you look close to such games you will see the main character is not moving forward or backward. That is the magic. The other things are actually moving. Got it?

Getting in to the Picture

The objects are created and placed in the world continuously in equal time interval in different patterns. This includes points or coins and obstacles. If you look at any such game you will find this pattern and the same pattern can come more than once.

Each time interval a pattern generator create patterns and based on the pattern objects will be placed in the world. At first the pattern is created for obstacles. Secondly the pattern is created for coins or points. While generating the second pattern we have to consider the pattern of obstacles. Got it?

The reason we are doing this is simple. When coins are placed in the world, ten or less coins can be placed in the line in an interval. We place coins continuously one by one. Say if the next position is occupied by an obstacle, we can place coin over the obstacle if it is a vehicle or do like this for hurdles by placing coins under hurdles. You got the picture right?

Once we finalize the patterns for the current time interval we can use the pattern to place the objects in the world and they will move towards main character ūüôā . In these type of games pattern generation is important. Patterns must be created without continuously repetition. If we generate same pattern continuously, it will be boring. We can customize the patterns on demand by giving behaviors and look and feel.

Hope this tutorial gave you a small idea about running games ūüôā

Developing a Mini Calculator Part-2

Hello, this is a continuation of article on Developing a Mini Calculator Part-1. In the first part I have explained about the components required for this application. Today we will see the implementation of Calculation Logic.

Note: I will be using Java programming language to demonstrate the examples

Calculation Logic

Since our calculator only support four operations and each of them take two operands and one operator it will be easy for us to write one single procedure or method which do all the necessary operation and return the result

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
        case '+': result = operand1 + operand2; break;
        case '-': result = operand1 - operand2; break;
        case '/': result = operand1 / opernad2; break;
        case '*': result = operand1 * operand2; break;
    return result;

The above given method is seems good but what will happen if you divide a number with zero. Yes of course division by zero is not possible. In that case what we will do. One way is to insert an error handling code that do the required when such and error comes. Again think of other scenario where the result is infinity or not a number. What we will do again insert some logic to handle that scenario.

Instead of keeping all calculations in one method we can separate them, like one method for addition, one four subtraction etc. Each of them will take three arguments and return the expected result.

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
       case '+': result = doAddition(operand1, operand2); break;
       case '-': result = doSubtraction(operand1, operand2); break;
       case '/': result = doDivision(operand1, operand2); break;
       case '*': result = doMultiplication(operand1 * operand2); break;
    return result;

private static double doAddition(double operand1, double operand2) {
    return (operand1) + (operand2);

private static double doSubtraction(double operand1, double operand2) {
    return (operand1) - (operand2);

private static double doDivision(double operand1, double operand2) {
    return (operand1) / (operand2);

private static double doMultiplication(double operand1, double operand2) {
    return (operand1) * (operand2);

Now we can manage each operation logic separately, say for division we can add extra error handling code

private static double doDivision(double operand1, double operand2) {
    double result = 0.0;
    try {
        result = operand1 / operand2;
    catch (ArithmeticException ex) {
        // set some flag to indicate this error
    if (new Double(result).isNaN()) {
        // set some flag to indicate this
        result = 0.0;
    } else if (!Double.isFinite(result)) {
        // set some flag to indicate this
        result = 0.0;
    return result;

If we look at the above program we will see two things. If the division leads to error we will set some flag and return zero. If the result is not a number or infinite we do the same. The flag might be some where else in the program. We have to introduce a state change some where out side the calculation logic. This is okay! because it doesn’t harm anything.

Instead of changing the state out side the calculation logic we can simply return the entire result out side the calculation logic. Say, the result, is it valid?, is it infinite?, is it an error. How we will do this?

public class Result {
    private double value;
    private boolean error;
    private boolean finite;
    private boolean nan;
    public Result() {
        // initialize to default
    // get and set methods will come here

We can create a new Result object to do this. This object will keep all the information related to the operation carried out. The Calculation Logic simply return the final result with necessary information to process the result. So an external module say Core can process the result as required without worrying about the calculations ūüôā

Calculation Logic: Do the required calculations and return the result
Core: Process the result and take the necessary actions

private static Result doDivision(double operand1, double operand2) {
    Result result = new Result();
    double value = 0.0;
    try {
        value = operand1 / operand2;
    catch (ArithmeticException ex) {
    if (new Double(value).isNaN()) {
    } else if (!Double.isFinite(result)) {
    return result;

Here ends the second part.¬†Hope you like it ūüôā

In the next part we will see the implementation of other modules.

Developing a Mini Calculator Part-1


Hello, today I will be talking about writing a simple mini calculator application which is capable of performing basic operations like addition, subtraction, multiplication and division.

The following are the application requirements

  • Addition, Subtraction, Multiplication and Division
  • Support for negative numbers and fractions
  • Record the operations performed by the user
  • Clear screen or history at any moment

Below is the possible structure of our calculator application based on the above requirement


In the above image we can see five modules and two end points. To give user the expected result a best possible connection or cooperation or communication between this five modules are required. Below we can find the details of each module

Calculation Logic

This is one of the main application modules. It contain a set of calculation logic. Since our calculator only have four operations defined which require two operands and one operator, the calculation logic will have three inputs.This will do the required calculation using the inputs and return the final result to Core module


This is where we maintain the application state. By state we mean the set of variables which makes application functional and so to give expected results. It will tell other modules do that or do this on demand. This is done by the use of state maintained in the core. Next application state will be a result of current application state and current user input. Simply states are memory of this application.

Input Service

This is responsible mainly for two related things, accepting user input and preventing user from giving a bad input. By bad input we mean any key press that will push the application into an abnormal state. Say for example you are entering a real number ‘65.06’. After entering six and five user may enter the period ‘.’ character twice. This is wrong because ’65..06 is not a valid number. So the second period is not valid and so we have prevent this. This service also manage the UI. All are done with the help of Core module.

Output Service

This module manage the state of screen or display and that is where we see the expected output based on our input. Core module will give the content to Output Service. By content we mean the state changes that are allowed to be on the display. Output Service is responsible to filter this public information from the content given by Core module

History Recorder

Responsible for recording the calculator history or simply it logs every right input which end up giving an expected result. Say ‘a + b = c’. it will record this as an entry in the log table

Here ends the first part. Hope You like it ūüôā

In the next part we will see¬†how to represent this things in¬†to object oriented program ūüôā


Algorithm to insert words into a 2D Matrix

The following algorithm can be used to put some selected words to a matrix without a specific order. Initially the matrix will be empty. Once we put the selected words, we put random alphabets to the empty cells. So by doing this we can hide these words in random position. The same can be used to generate the Find Word puzzles

There are total eight possible directions possible, they are NORTH(0), NORTH-EAST(1), EAST(2), SOUTH-EAST(3), SOUTH(4), SOUTH-WEST(5), WEST(6), NORTH-WEST(7)

The algorithm is given below

global matrix[10, 10]

procedure insert_word_to_matrix(word)
  directions <- [0, 1, 2, 3, 4, 5, 6, 7]
  completed <- NO
  tries <- 5
  while not completed
    if tries reached 0
      exit this while loop
    (x_position, y_position) <- Locate an empty box randomly
    next_direction <- 0
    while next_direction is less than 8
      (x_increment, y_increment) <- get_direction_increment(directions[next_direction])
      if possible_to_insert((x_position, y_position), (x_increment, y_increment), word)
        do_insert_word((x_position, y_position), (x_increment, y_increment), word)
        completed <- YES
        exit this while loop
      next_direction <- next_direction + 1
    tries <- tries - 1
  if completed
    return YES
  return NO

procedure get_direction_increment(direction)
  if direction = 0 return (-1, 0)  
  else if direction = 1 return (-1, 1)
  else if direction = 2 return (0, 1)
  else if direction = 3 return (1, 1)
  else if direction = 4 return (1, 0)
  else if direction = 5 return (1, -1)
  else if direction = 6 return (0, -1)
  else if direction = 7 return (-1, -1)

procedure possible_to_insert((x_position, y_position), (x_increment, y_increment), word)
  word_length_counter <- 1
  while word_length_counter is less than length(word)
    (next_x_position, next_y_position) <- (x_position + x_increment, y_position + y_increment)
    if (next_x_position, y_position) is outside the matrix
      return NO
    else if matrix[next_x_position, next_y_position] have no value
      word_length_counter <- word_length_counter + 1
      continue while loop
    else if matrix[next_x_position, next_y_position] is not equal to word[word_length_counter]
      return NO
    word_length_counter <- word_length_counter + 1
    continue this while loop
 return YES

procedure do_insert_word((x_position, y_position), (x_increment, y_increment), word)
  word_length_counter <- 1
  matrix[x_position, y_position] <- word[0]
  while word_length_counter is less than length(word)
    (next_x_position, next_y_position) <- (x_position + x_increment, y_position + y_increment)
    matrix[next_x_position, next_y_position] <- word[word_length_counter]
    word_length_counter <- word_length_counter + 1
    continue this while loop

Note: Here we try to fit the word by taking each direction from the list for a selected position. This is some times time consuming. So we can try another method. First find the best fit directions (at least three) for the selected word using the matrix boundary and word length. Check if it is possible to fill in any of the selected direction.So by doing this we can improve the performance

Hope this tutorial was helpful ūüôā

Thanks for Reading

SQLite Programming in Java (Part 1)

This tutorial is an introduction to SQLite programming in Java and it explains how we can establish a connection to SQLite database from Java application.

About SQLite
SQLite is a software library which implements SQL database engine, which is self-contained and serverless means no server that needs to be started, stopped or configured and is zero configuration means no setup or installation required.

Using SQLite with Java
The below given program demonstrate the steps required to establish connection to the sqlite database. For the sake of simplicity i have divided the program into different parts.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

About DriverManager class
It is responsible for managing Java DataBase Connectivity (JDBC) drivers.

About Connection class
To establish connection with the database, java applications which make use of JDBC API has to obtain instance of Connection class first. The DriverManager class provides getConnection(String url) method which will create and return a Connection object. The url provides a way to identify the database using a protocol. The URL format for SQLite is given below.


In the above url you can replace string “dbname” with your database¬†name. SQLite database is a file which ends with a “.db” extension and it¬†will be cross platform.

About Statement class
Once you obtain connection to database, your next job is to create an instance of Statement class. Statement objects are used to obtain results by executing static SQL statements and they can be used to execute both Data Definition Language (DDL) commands and Data Manipulation Language (DML) commands. Statement class provides executeQuery(command) method to execute DML commands and executeUpdate(command) method to execute DDL commands.Simply statement object send the commands to the database and get results back.

The below given code block shows, how we can integrate this two together.

connection = DriverManager.getConnection("jdbc:sqlite:test.db");
statement = connection.createStatement();

Why do we use forName(url) method
The forName(url) method is used to load any class whose complete name is specified as the url at run time. Here this will load the JDBC class from org.sqlite package.

What goes wrong and how should we treat them

  • When we call the forName(url) method, if the class is not available at run time it will throw ClassNotFoundException
  • When we call getConnection() method, if the url is null or any access error occur this will throw SQLException
  • When we call createStatement() method, if there are any access error occur or a¬†closed connection this will throw SQLException

So we must write this three statements inside the try-catch-finally block.

How to close the connection and quite the application
Its simple, we close active statement and connection. Both Connection class and Statement class have a method called close() which releases connection or statement object’s JDBC and database resources once called. First you should close the statement by calling¬†close() method of statement object and then close() method of connection object. The reverse order is not recommended.

Please find below the complete sample program

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

public class SQLiteJavaDemo {
    public static void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection("jdbc:sqlite:demo.db");
            Statement st = con.createStatement();
            System.out.println("Connection created.");
            System.out.println("Connection closed.");
        } catch (SQLException | ClassNotFoundException ex) {

In Part-2 we will see how to use statement object to execute sql commands.