As you can see, I haven't updated this blog in quite some time! Schools in South Africa have, for some reason, switched to using mostly Delphi and the Java space grew quiet. As for my business, I moved from Java to Scala and Kotlin, especially for mobile development on Android.
Of late, I've been making use of Dart and Flutter, with a bit of Kotlin and Swift, to develop mobile applications. You can find some more information and programming tips at https://www.nofuss.co.za. As always, I'm happy to try and assist where I can!
Friday, May 10, 2019
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:
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!
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!
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.
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!
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
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 ();
}
}
Wednesday, March 7, 2012
JavaK has been updated with a new Java GUI primer. If you've never done any Java Swing development, this short tutorial will take you through the steps and have you building GUI's in no time.
Wednesday, February 29, 2012
A student asked me if there's a simple way of making a method that takes a variable number of arguments. In Java, using the ... notation, you can do just that!
Let's say, for example, you want to create a method that will add up any number of integer numbers. Using the code below, you can do just that. So simple, so easy, so elegant.
public class AddUpMany
{ public int addThemAll(int... numbers) { int total = 0; for (int temp : numbers)
{ total += temp; } return total; } public static void main(String args[])
{ AddUpMany instance = new AddUpMany(); System.out.println("Adding up 5 and 6 gives you " + instance.addThemAll(5,6)); System.out.println("Adding up 5,5 and 2 gives you " + instance.addThemAll(5,5,2)); System.out.println("Adding up 1,2 and 3 gives you " + instance.addThemAll(1,2,3)); } }
Saturday, February 25, 2012
Javascript Lessons
It's so often these days that I get asked questions around Javascript, that I felt I should find a resource for my students. After digging around a bit, I found Code Academy, a brilliant site that offers a free Javascript course.
Why Javascript if this site is about Java? Well, some students have started to write all sorts of interesting applications as projects, especially in the mobile space. With smart-phones all the rage these days, and, admit it, some of these devices are incredible, more and more students are interested in developing for them. By using Java as the back-end, they write server applications with a HTML / Javascript interface.
If you are interesting in learning Javascript for free, I'd recommend you give the Code Academy guys a try, it's a great site, with really easy-to-follow lessons that will get you up to speed in just a couple of hours.
Why Javascript if this site is about Java? Well, some students have started to write all sorts of interesting applications as projects, especially in the mobile space. With smart-phones all the rage these days, and, admit it, some of these devices are incredible, more and more students are interested in developing for them. By using Java as the back-end, they write server applications with a HTML / Javascript interface.
If you are interesting in learning Javascript for free, I'd recommend you give the Code Academy guys a try, it's a great site, with really easy-to-follow lessons that will get you up to speed in just a couple of hours.
Monday, September 6, 2010
Another one in Stellenbosch - Umonya
It's happening again!
There's ANOTHER free Python course being held by Umonya at the University of Stellenbosch. Students will be given the opportunity to learn the Python programming language, interact with industry players and, most importantly, learn that computers are not all that scary.
Please visit Umonya for more information regarding this fantastic outreach project.
There's ANOTHER free Python course being held by Umonya at the University of Stellenbosch. Students will be given the opportunity to learn the Python programming language, interact with industry players and, most importantly, learn that computers are not all that scary.
Please visit Umonya for more information regarding this fantastic outreach project.
Tuesday, August 31, 2010
Great stuff in Cape Town
The guys at Umonya are doing fantastic things for school kids in South Africa. They offer free Python courses over selected weekends where children with no previous programming experience are taught how to program in Python.
Not only do they show these kids things they might have thought impossible before, but they also make time to have chats with the kids to open their eyes to career possibilities that many of them have never thought off.
The courses are organized by UCT students, but, in my humble opinion, reflect the same level of quality, commitment and dedication one would expect from professional trainers. These guys need your help and support, so if your company (or yourself) can be involved in any way, do step up and help cultivate the next generation of IT professionals for Africa.
Not only do they show these kids things they might have thought impossible before, but they also make time to have chats with the kids to open their eyes to career possibilities that many of them have never thought off.
The courses are organized by UCT students, but, in my humble opinion, reflect the same level of quality, commitment and dedication one would expect from professional trainers. These guys need your help and support, so if your company (or yourself) can be involved in any way, do step up and help cultivate the next generation of IT professionals for Africa.
Friday, August 20, 2010
Telesure Cesspool
I know this is not blog related, but really, I've had it with these guys.
RANT ON
We had an accident in April 2010, and things are STILL not sorted out by these Telesure, Auto&General, AA Insurance incompetents. Did you know Dial Direct, Budget, Auto & General and First for Woman are ALL just brands of Telesure? And if you go on a site like Hippo, you are actually getting quotes from the same company, just under different brand names.
So here's a little bit of free advice - stay away from Telesure and their brands, it's just the most pathetic service I have ever received. In fact, I'm going to write a nice long article about it and hopefully save someone all the hassle I had to go through. It takes days for them to get back to you, even though they have a so-called service charter that they clearly do not stick to.
Do proper research when you are considering your insurance provider and make sure they are underwritten by a reputable company. I made the mistake of trusting in the AA brand name, AA Insurance is useless, they are simply brokers and did not lift a finger to try to assist us.
RANT OFF
RANT ON
We had an accident in April 2010, and things are STILL not sorted out by these Telesure, Auto&General, AA Insurance incompetents. Did you know Dial Direct, Budget, Auto & General and First for Woman are ALL just brands of Telesure? And if you go on a site like Hippo, you are actually getting quotes from the same company, just under different brand names.
So here's a little bit of free advice - stay away from Telesure and their brands, it's just the most pathetic service I have ever received. In fact, I'm going to write a nice long article about it and hopefully save someone all the hassle I had to go through. It takes days for them to get back to you, even though they have a so-called service charter that they clearly do not stick to.
Do proper research when you are considering your insurance provider and make sure they are underwritten by a reputable company. I made the mistake of trusting in the AA brand name, AA Insurance is useless, they are simply brokers and did not lift a finger to try to assist us.
RANT OFF
Wednesday, March 10, 2010
Python in Afrika
Ja, ek't ook besluit om meer ernstig te raak oor my Python-vaardighede, so ek het 'n nuwe blog by PythonOutjie opgelaai en gaan my avonture met almal deel :)
Friday, March 5, 2010
Excellent resource for code examples
Looking for Java example code? Why not give Java2S a try? They have thousands of code listings and you will be surprised just how broad the subjects range.
Have fun and remember to keep in touch with your Java basics, that's a lesson we often forget!
Have fun and remember to keep in touch with your Java basics, that's a lesson we often forget!
Friday, February 12, 2010
Jython book and tutorial
Hi.
For those that are interested in the Jython programming language, there is a new Jython Book available. Go check it out for excellent tutorials and a general overview of the Jython Language.
For those that don't know, Jython is a Python implementation for the Java Virtual Machine. This allows Python developers to use Java libraries and Java developers to use Python code. It's a great tool!
For those that are interested in the Jython programming language, there is a new Jython Book available. Go check it out for excellent tutorials and a general overview of the Jython Language.
For those that don't know, Jython is a Python implementation for the Java Virtual Machine. This allows Python developers to use Java libraries and Java developers to use Python code. It's a great tool!
Broadband internet access
President Zuma appears to understand that we need better (and more affordable) access to the internet in South Africa if we are to compete globally, especially with regards to education.
See this article about his speech for more information.
See this article about his speech for more information.
Thursday, February 4, 2010
Nuwe Borg
Dis 'n nuwe jaar en daar is baie veranderinge wat kom. JavaK het nog 'n borg gekry (http://www.cruiselinecrew.co.za) en ons het groot planne vir die jaar. Die blog sal meer gereeld opgedateer word en ons het verskeie nuwe artikels wat ons op http://www.javak.co.za gaan plaas. Boekmerk ons as jy Java take of huiswerk het en kom loer gerus dan en wan in om te sien wat is nuut.
NetBeans 6.8
Oor die afgelope paar weke heen het verskeie studente my gevra watter IDE (redigeer omgewing) ek gebruik vir my Java ontwikkeling. Ek gebruik al vir 'n paar jaar lank die http://netbeans.org/ omgewing om my Java projekte in te doen. Gaan loer gerus in by hulle webwerf vir meer inligting.
Subscribe to:
Posts (Atom)