Friday, September 28, 2012

Formatting blog code snippets

I use http://codeformatter.blogspot.com/ to format the code snippets. It's brilliant, do give it a try if you are posting code to your blog.

How to determine the next occurrence of a day of the week in Java

I recently ran into a question around how to determine the next occurrence of a particular day of the week in Java. For example, if today is Tuesday, how do I figure out when the next Saturday is? Or, if it's Saturday, when is the next Wednesday?

Sounds simple enough, right? Turns out, it's not that easy in Java! Here's my solution:


 public static Date getNextOccurenceOfDay(Date today, int dayOfWeek) {  
  Calendar cal = Calendar.getInstance();  
  cal.setTime(today);  
  int dow = cal.get(Calendar.DAY_OF_WEEK);  
  int numDays = 7 - ((dow - dayOfWeek) % 7 + 7) % 7;  
  cal.add(Calendar.DAY_OF_YEAR, numDays);  
  return cal.getTime();  
 }  

Turns out that the % (mod) in Java doesn't deal with negative numbers that well, but by using the trick of doing a double-mod, you get the right answer!

You simply call this method with the starting date, and then tell it to target, for example, Calendar. SATURDAY, and it will give you the date of the next Saturday!

Friday, September 21, 2012

Finding duplicate numbers with Binary Math in Java

I went for an interview once, and was asked the following question:

Given a sequence of numbers, from 1 to 1000, where only one number is duplicated, how would I proceed to find the duplicate number?

After I solved the problem using a basic loop that just checks if it's seen this number before using a hash table, the interviewer asked if I could improve my answer using XOR math. I didn't quite get it right, this is the solution they showed me :

int numbers[] = {4,2,3,4,5,6,7,8,1,10,11,12,13,14,9};

for (int pos = 1; pos < numbers.length; pos++)
{
  numbers[pos] = numbers[pos] ^ numbers[pos-1] ^ pos;
}

System.out.println("Duplicate is : " + numbers[numbers.length-1]);


This bit of Java code loops through the array and finds the duplicate number. Of course, this only works for positive integers, I've not tested it with negative numbers and I know it doesn't work with floats.

So, there you go, a good use for binary math in Java!

Tuesday, September 18, 2012

Learning Python with Umonya

It's time for some more Python fun!  Umonya is busy gearing up for another basic Python course aimed at high school pupils.

I quote from their website :

"Umonya will be having a course on 12-14 October 2012 where we will teach 100 High School children how to program in Python. It will be taking place during Cape Town's first ever Software week."

If you are interested, please visit their website at http://www.umonya.org/ to learn more.

Thursday, June 7, 2012

Counting words in a string

I had a question this morning from a student, asking when using a pattern matcher, if he could count the number of "hi" words in a string that didn't start with an "x".

Of course you can!


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountOccurences {
  
  // Our test string has 5 occurences.
  private static String input_string = "hi lo and xhi xhi hihi loxhihixhihi";
  
  public static void main(String args[]) {
    int count = 0;
    Pattern pattern = Pattern.compile("[^x]*hi");
    Matcher matcher = pattern.matcher(input_string);
    
    while (matcher.find()) {
      count++;
    }
    
    System.out.println("The final count is " + count);
  } 
}
  
Now I'll leave it as an exercise for you to go read up on Regular Expressions...

Friday, May 11, 2012

JavaK now has a GitHub repository. We will be uploading all of our source code there, as well as the various tutorials that we have released.

Find the GitHub entry for JavaK here - https://github.com/ewaldhorn/javak

Thursday, April 19, 2012

There's a PDF going around that I wrote a few years ago with a Database tutorial in it for Java. I've been asked to please release the source code, so, here it is. This code will connect to a Microsoft Access database file on the local system and allow you to read and write via JDBC.
/**
 * Opens a Microsoft Access Database without having need to
 * have access rights to the Administrative Tools on Windows
 * to set up any ODBC connections.
 */

import java.sql.*;
import java.io.*;

/**
 * @author Ewald Horn
 * @company JavaK
 */
public class ConnectDB
{

   public static Connection con;
   public static final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
   public static final String url = "jdbc:odbc:" +
       "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=";

   String path; // where the database can be found

   ////////////////////////////////////////////////////////////
   /**
    * Sets the path to the database.
    */
   public ConnectDB ()
   {
       path = "c:" + File.separator + "projects" +
           File.separator + "tutorial.mdb";
   }


   ////////////////////////////////////////////////////////////
   /**
    * Runner method for the TestAccess class.
    */
   public void go ()
   {
       makeConnection ();
       addRecipe ();
       removeRecipe ();
       updateRecipe ();
       showRecipes ();
       closeConnection ();
   }


   ////////////////////////////////////////////////////////////
   /**
    * Creates the database connection.
    */
   private void makeConnection ()
   {
       System.out.println ("Opening database...\n");
       try
       {
           Class.forName (driver);
           con = DriverManager.getConnection (url + path);
       }
       catch (Exception ex)
       {
           System.out.println ("Error opening the database!");
           System.out.println (ex);
           System.exit (0);
       }
       System.out.println ("Success!");
   }


   ////////////////////////////////////////////////////////////
   /**
    * Removes a recipe from the database.
    */
   private void removeRecipe ()
   {
       String sql = "DELETE FROM RECIPESTABLE WHERE RECIPEID=11";
       System.out.print ("\nRemoving a recipe : ");

       try
       {
           Statement statement = con.createStatement ();
           int result = statement.executeUpdate (sql);
           System.out.println (" Removed " + result + " recipe(s).");
       }
       catch (Exception ex)
       {
           System.out.println ("Error removing a recipe!");
           System.out.println (ex);
       }
   }


   ////////////////////////////////////////////////////////////
   /**
    * Modifies an existing record.
    */
   private void updateRecipe ()
   {
       String sql = "UPDATE RECIPESTABLE SET " +
           "RECIPENAME='Pizza' WHERE RECIPEID=8";
       System.out.print ("Updating a record : ");
       try
       {
           Statement statement = con.createStatement ();
           int result = statement.executeUpdate (sql);
           System.out.println (" Updated " + result + " recipe(s).");
       }
       catch (Exception ex)
       {
           System.out.println ("Error removing a recipe!");
           System.out.println (ex);
       }
   }


   ////////////////////////////////////////////////////////////
   /**
    * Adds a recipe to the database.
    */
   private void addRecipe ()
   {
       String sql = "INSERT INTO RECIPESTABLE(RECIPENAME,INGREDIENTS)" +
           " VALUES('Any Recipe','Ingredients')";

       System.out.print ("\nAdding a recipe : ");

       try
       {
           Statement statement = con.createStatement ();
           int result = statement.executeUpdate (sql);
           System.out.println (" Added " + result + " recipe(s).");
       }
       catch (Exception ex)
       {
           System.out.println ("Error adding a recipe!");
           System.out.println (ex);
       }
   }


   ////////////////////////////////////////////////////////////
   /**
    * Displays all the recipes in the database.
    */
   private void showRecipes ()
   {
       String sql = "SELECT * FROM RECIPESTABLE";

       System.out.println ("\nRecipes in the database : \n");

       try
       {

           Statement statement = con.createStatement ();
           ResultSet rs = statement.executeQuery (sql);

           if (rs != null)
           {
               while (rs.next ())
               {
                   int recipeID = rs.getInt ("RECIPEID");
                   String recipeName = rs.getString ("RECIPENAME");
                   System.out.println (recipeID + " " + recipeName);
               }
           }

           rs.close ();
           statement.close ();

       }
       catch (Exception ex)
       {
           System.out.println ("Error reading database information!");
           System.out.println (ex);
       }
   }


   ////////////////////////////////////////////////////////////
   /**
    * Closes the connection cleanly.
    */
   private void closeConnection ()
   {
       System.out.println ("\nClosing database.");
       try
       {
           con.close ();
       }
       catch (Exception ex)
       {
           System.out.println ("Error closing the database!");
           System.out.println (ex);
       }
   }


   ////////////////////////////////////////////////////////////
   /**
    * Main method for ConnectDB.java
    */
   public static void main (String args[])
   {
       ConnectDB testApp = new ConnectDB ();
       testApp.go ();
   }
}