Verifying Input

When creating constructors and adding setters, I’ve been taught to verify all input passed to the method. In working through the ProjectEuler exercises, I’ve made use of helper methods that hadformal parameters but didn’t necessarily verify the input (bad habit). With Problem8, I decided to put this into practice. The problem was: “find the greatest product of five consecutive digits in a 1000-digit number.’ I solved this problem using 2 for loops:

  1. With the first for loop, I created a String object that contained 5 characters at one time. With every iteration of the for loop, the sentinel would be updated by 1 and thus, the String would be updated to contain a new sequence of 5 characters e.g.  startingString.substring(i,i+4).
  2. Rather than perform the required computation in the 1st for loop which would made my program faster, I decided to create a helper method which would accept a String and return the product of all the digits in that String. 
  3. The first iteration of my helper method didn’t include any checks to verify that the String didn’t have any non-word characters which would have caused a NumberFormat exception (I converted the digits in the String object using Integer.parseInt(String name)).
    Java-numberformat

     So, I added some to the helper method I used to make sure that the algorithm would return correct/appropriate output when provided input that fits the formal parameter specifications. 

  4. First, I stripped the String of all non-word characters with this command: digits.replaceAll(“\W”,””); An alternate and informative way to alert the user to the ‘bad’ input is via the try { } catch { } feature of Java.
  5. Another thing to check for is if, after stripping all non-word characters from the String passed to the helper method, the String’s length is 0 i.e. the String is an empty String, I would return 0 as the product of the String in that case instead of the value of Product which was initialized to 1. That was taken care of via a simple conditional statement. Here’s the code for my helper method: 

    https://gist.github.com/1531024

Overall, it’ll be good practice for me to view my code with an eye to splitting off ‘tasks’ into helper methods and making sure that input is verified. 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s