<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ryan Rampersad &#187; Java</title>
	<atom:link href="http://blog.ryanrampersad.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ryanrampersad.com</link>
	<description>Thoughts, Ideas &#38; Opinions</description>
	<lastBuildDate>Thu, 17 May 2012 17:11:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-beta4-20825</generator>
		<item>
		<title>★ More On Shuffling An Array Correctly</title>
		<link>http://blog.ryanrampersad.com/2012/03/03/more-on-shuffling-an-array-correctly/</link>
		<comments>http://blog.ryanrampersad.com/2012/03/03/more-on-shuffling-an-array-correctly/#comments</comments>
		<pubDate>Sun, 04 Mar 2012 02:51:13 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[charts]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4758</guid>
		<description><![CDATA[I wrote on how to shuffle an array in Java nearly four years ago. Since then, it has come to my attention that the algorithms presented in that original post are wrong and definitely incomplete. Commenter Ken Arnold pointed this out and I was very curious to see some data on the variability of randomization [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote on <a href="http://blog.ryanrampersad.com/2008/10/13/shuffle-an-array-in-java/">how to shuffle an array in Java</a> nearly four years ago. Since then, it has come to my attention that the algorithms presented in that <em>original</em> post are wrong and definitely incomplete. Commenter Ken Arnold pointed this out and I was very curious to see some data on the variability of randomization using the original algorithm, his modified version and another powered my the built in <code>Collections</code> shuffle method in Java.</p>
<p>This all pertains to the randomness of <em>cards</em> and specifically the distribution of cards when shuffled from a fresh deck. Following that, any state after that initial shuffle is harder to predict but it may still be predictable. You can view the original algorithm defined in the <a href="http://blog.ryanrampersad.com/2008/10/13/shuffle-an-array-in-java/">original post</a> from <a href="http://leepoint.net/notes-java/algorithms/random/random-shuffling.html">Leepoint</a>. However, while this example is clearly defined in the context of cards, it is not strictly deck-card based &#8211; if you need to randomize any set, using that original algorithm probably will not yield the results you are looking for. You will see why soon.</p>
<p>The modified version runs along these lines.</p>
<pre class="brush: java; title: ; notranslate">
public static int[] getOriginalShuffledDeck() {
  Random rnd = new Random();
  int[] cards = new int[52];
   
  for (int i = 0; i &lt; cards.length; i++) {
    cards[i] = i;
  }
  
  for (int i = 0; i &lt; cards.length; i++) {
    int position = i + rnd.nextInt(cards.length - i);
    int temp = cards[i];
    cards[i] = cards[position];
    cards[position] = temp;
  }
  return cards;
}
</pre>
<p>Aside from the minor stylistic differences, the major logical difference is the in the declaration of the <code>position</code>. The <code>i + rnd.nextInt(cards.length - i)</code> changes the position properly, so that elements are not repeatedly moved around the deck of cards. I am not entirely sure of the logic here &#8211; an example chart could be useful, but I&#8217;ll leave that to you.</p>
<p>The other algorithm I tested against was the built-in <code>Collections.shuffle</code> randomization. It appears that this method is consistent with the modified method above, which is good to know. Because there is a lack of shuffling for a regular non-object array, there is a cumbersome conversion between Integer objects and an ArrayList and then back to regular <code>ints</code>.</p>
<pre class="brush: java; title: ; notranslate">
public static int[] getCollectionsShuffledDeck() {
  int[] cards = new int[52];
  ArrayList&lt;Integer&gt; cards_objs = new ArrayList&lt;Integer&gt;(); 
  
  for (int i=0; i &lt; cards.length; i++) {
     cards_objs.add(i);
  }

  Collections.shuffle(cards_objs);
  
  for (int i = 0; i &lt; cards.length; i++) {
    cards[i] = cards_objs.get(i);
  }
  
  return cards;
  
}
</pre>
<p>With those three methods, I ran a test with each. I ran one million iterations of randomizing fresh decks of cards. I recorded each position (position 0 to 51) and each card in those positions (card 0 to 51, because we don&#8217;t actually care which card, just that they&#8217;re all uniquely identifiable) and the number of times they appeared in those million trials. So without further ado, look at the astoundingly poor <em>randomness</em> generated by the <em>original</em> algorithm.</p>
<p><a href="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/original-random.png"><img src="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/original-random-580x391.png" alt="The Original Method" title="The Original Method" width="580" height="391" class="aligncenter size-medium wp-image-4761" /></a></p>
<p>The spikes are where there is an obvious failure. I am definitely not a statistician but I can guarantee this is not a great distribution of what is supposed to be random values, especially when the number of trials is so high. With that said, I think it is quite clear that <strong>the original method of randomizing a deck of cards is flawed</strong>. Now, that&#8217;s not to say it is not random, since there is some randomness there, but just not enough. Now, on to the modified method&#8217;s chart.</p>
<p><a href="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/modified-random.png"><img src="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/modified-random-580x388.png" alt="Modified Random" title="Modified Random" width="580" height="388" class="aligncenter size-medium wp-image-4762" /></a></p>
<p>The distribution here is much better. It just so happens that one million divided by 52 is approximately 19230, which is what most of these position-card indexes reach. Clearly, the modified version is better in this case.</p>
<p><a href="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/collections-random.png"><img src="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/collections-random-580x390.png" alt="" title="Collections Random" width="580" height="390" class="aligncenter size-medium wp-image-4763" /></a></p>
<p>The <code>Collections.shuffle</code> random was about the same. This is a great benefit of using the built in routine because you know that this way, it will always be <em>random</em> with that great low variance. That&#8217;s not to say there aren&#8217;t highs and lows in these two data sets, but it is lesser than the original. I want to be clear though: this may seem at first limited to strictly a card-deck problem but this could present itself anywhere that something starts ordered and needs to be non-ordered after some operation. You may need to randomize your genome project, your particle layout or maybe even your favorite file cabinet. </p>
<p>You can grab the <a href="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/RandomStuff.txt">testing program</a> and the <a href="http://blog.ryanrampersad.com/wp-content/uploads/2012/03/rnds.xlsx">excel file for the raw data</a> used to make the charts.</p>
<p><em>Update</em>: You can read an interesting Stack Overflow question on, &#8220;<a href="http://stackoverflow.com/questions/9701639/is-collections-shuffle-really-random-enough-practical-examples-seem-to-deny-t">Is Collection.shuffle random enough?</a>&#8220;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2012/03/03/more-on-shuffling-an-array-correctly/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>★ Java: the left-hand side of an assignment must be a variable</title>
		<link>http://blog.ryanrampersad.com/2012/02/29/java-the-left-hand-side-of-an-assignment-must-be-a-variable/</link>
		<comments>http://blog.ryanrampersad.com/2012/02/29/java-the-left-hand-side-of-an-assignment-must-be-a-variable/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 17:48:03 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Errors]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[assignment]]></category>
		<category><![CDATA[error]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4438</guid>
		<description><![CDATA[After programming in Scheme for months, going back to Java can cause some problems as you can imagine. I encountered this error a few days ago while writing just the simplest searching loop. It&#8217;s your typical searching for the largest value loop. It&#8217;s nothing special, but then again, it doesn&#8217;t work. At least the error [...]]]></description>
			<content:encoded><![CDATA[<p>After programming in Scheme for months, going back to Java can cause some problems as you can imagine. I encountered this error a few days ago while writing just the simplest searching loop.</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String[] args) {
	int[] arr = new int[] {2804, 2374, 6382, 1899};
	
	int index = 0, largest = arr[0];
	for (int i = 1; i &lt; arr.length; i++) {
		(if largest &gt; arr[i]) {
			index = i;
			largest = arr[i];
		}
	}
}
</pre>
<p>It&#8217;s your <a href="http://blog.ryanrampersad.com/2011/05/11/ap-computer-science-2011-free-response-3/">typical searching for the largest value loop</a>. It&#8217;s nothing special, but then again, it doesn&#8217;t work.</p>
<p>At least the error message is logical. No, not really.</p>
<blockquote><p>the left-hand side of an assignment must be a variable</p></blockquote>
<p>By studying very carefully and fully realizing that I am still in <em>scheme</em> mode, I notice that there is a parenthesis before the if-statement instead after the <code>if</code> keyword itself. Had I been helping someone else with this code and they showed me that error message along with this, would I have known it was a misplaced parenthesis? No way. I&#8217;d eliminate one possibility at a time by removing each successive layer of expressions and assignments until it stopped. I might even go so far as to retype the entire thing. It&#8217;s subtle.</p>
<p>It also <a href="http://stackoverflow.com/questions/3639695/the-left-hand-side-of-an-assignment-must-be-a-variable-problem-with-charat">turns out that if you try to assign a value to a method</a>, you&#8217;ll cause this error too.</p>
<p class="signoff"><em>Happy language switching!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2012/02/29/java-the-left-hand-side-of-an-assignment-must-be-a-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>★ Java: syntax error on token &#8220;else&#8221;, delete this token</title>
		<link>http://blog.ryanrampersad.com/2012/02/22/java-syntax-error-on-token-else-delete-this-token/</link>
		<comments>http://blog.ryanrampersad.com/2012/02/22/java-syntax-error-on-token-else-delete-this-token/#comments</comments>
		<pubDate>Wed, 22 Feb 2012 17:46:09 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Errors]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[token]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4432</guid>
		<description><![CDATA[Before school ended, I donated some of my time to helping out the Intro to Java kids. In that class, I realized that when you tell beginning programmers &#8220;End each line with a semi-colon,&#8221; they think you really mean it. As in, every single line with actual code (e.g. not brackets) must end with a [...]]]></description>
			<content:encoded><![CDATA[<p>Before school ended, I donated some of my time to helping out the Intro to Java kids. In that class, I realized that when you tell beginning programmers <em>&#8220;End each line with a semi-colon,&#8221;</em> they think you really mean it. As in, every single line with actual code (e.g. not brackets) must end with a semi-colon. Well, it&#8217;s sad news but that is not true. Not every line needs a semi-colon.</p>
<p>Here&#8217;s an example. Look at this code. I dare you even to try running it. You&#8217;ll end up with an error.</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String[] args) {
	int magic = 10;
	if (magic &lt; 20);
	{
		System.out.println(&quot;weak magic&quot;);
	} 
	else
	{
		System.out.println(&quot;strong magic&quot;);
	}
}	
</pre>
<p>The error is of course, uncommunicative of the true problem. Did you spot the error yet?</p>
<blockquote><p>syntax error on token &#8220;else&#8221;, delete this token</p></blockquote>
<p>The problem here isn&#8217;t the <code>else</code> or even the <code>if</code>. No, the problem is a <em>semi-colon</em>. Seriously. Take a look at the if-statement expression. The oddity comes about when you actually see the semi-colon attached to the end of it. And because the if-statement ended there, the <code>else</code> has no preceding pair so it has no choice but to error out.</p>
<p>This example is actually a clear cut case of putting a semi-colon after an if-statement expression. Imagine you didn&#8217;t have an error to remind you what you just did. You might just have a plain statement and proper following brackets.</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String[] args) {
	int magic = 10;
	if (magic &lt; 20); {
		System.out.println(&quot;weak magic&quot;);
	}  
}
</pre>
<p>Without the <code>else</code> to throw an error message up, how easy would this be to spot? It&#8217;s tricky. What if your if-case was a rare edge case condition that you were hard pressed to demonstrate in testing but you theoretically knew it existed? You&#8217;d almost never know this wasn&#8217;t work until your nuclear reactor began to melt down.</p>
<p>The moral of story: kids will do what you tell them and mind you semi-colons at the end of constructs.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2012/02/22/java-syntax-error-on-token-else-delete-this-token/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>★ Java: Duplicate local variable</title>
		<link>http://blog.ryanrampersad.com/2012/02/15/java-duplicate-local-variable/</link>
		<comments>http://blog.ryanrampersad.com/2012/02/15/java-duplicate-local-variable/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 17:44:19 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Errors]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[duplication]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[variable]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4430</guid>
		<description><![CDATA[It&#8217;s usually easy to catch errors in Java, either through the IDE you&#8217;re using or at compile time. Recently, I helped a friend taking a course in Java with an error he was getting in a lab he was working on. It mentioned something about a duplicate variable. Duplicate local variable Unfortunately, I didn&#8217;t grab [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s usually easy to catch errors in Java, either through the IDE you&#8217;re using or at compile time. Recently, I helped a friend taking a course in Java with an error he was getting in a lab he was working on. It mentioned something about a duplicate variable.</p>
<blockquote><p>Duplicate local variable</p></blockquote>
<p>Unfortunately, I didn&#8217;t grab his erring source code earlier, so I can&#8217;t give the true real world source. Nevertheless, my own crafted code should illuminate the problem sufficiently.</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String[] args) {
	
	int magic = 10;
	if ( 10 &lt; 11 ) {
		int magic = 12;
		magic++;
	}
	
}
</pre>
<p>Imagine you had a variable declaration and initialization at the top of some method. Then later you attempt to create another variable with the same name as before, but inside of a construct like a <em>for loop</em> or <em>if</em>. Unwittingly, you have attempted to redeclare an already declared variable.</p>
<p>Why doesn&#8217;t the IDE or compiler know that it&#8217;s a syntax error in that case, and that you obviously cannot redeclare variables? Java&#8217;s just funny like that, but I suspect it has something to do with the scoping rules in Java. The <code>magic</code> variable inside of the if-statement should be separate, and it is telling you it&#8217;s a duplicate, not that it isn&#8217;t allowed. So I suppose that&#8217;s helpful.</p>
<p>In short, the easy fix is to <em>rename</em> the inner-conflicting variable. So the <code>magic</code> that&#8217;s in the if-statement could be <em>magic2</em> and anything that references it in the if should also be updated. That&#8217;s clear enough. The other possibility is to remove the <code>int</code> declaration. Imagine you were simply setting value instead of declaring. It&#8217;s an easy mistake to make, especially when you&#8217;ve a bunch of declarations repeated.</p>
<p class="signoff">Happy deduplicating!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2012/02/15/java-duplicate-local-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>★ Correct Change in Java</title>
		<link>http://blog.ryanrampersad.com/2011/11/30/correct-change-in-java/</link>
		<comments>http://blog.ryanrampersad.com/2011/11/30/correct-change-in-java/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 17:24:53 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4147</guid>
		<description><![CDATA[When I was a freshmen in high school, one our earliest programs was to find the correct change for some number of cents. I remember when I wrote that first program, I did it an atypical way and got some strange looks. Instead of using nested modulus like everyone else, I used integer division and [...]]]></description>
			<content:encoded><![CDATA[<p>When I was a freshmen in high school, one our earliest programs was to find the correct change for some number of cents. I remember when I wrote that first program, I did it an atypical way and got some strange looks. Instead of using nested <em>modulus</em> like everyone else, I used integer division and then subtracted out the difference from a running total.</p>
<p>Years later, I thought it would be cool to redo that program and it certainly was fun. I used the same methodology in fact, but with a couple of optimizations.</p>
<p>I start the program off by creating a Scanner object for user input and a prompt.</p>
<pre class="brush: java; title: ; notranslate">
Scanner scanner = new Scanner(System.in);
System.out.println(&quot;Enter some amount in cents: &quot;);
int cents = scanner.nextInt();
</pre>
<p>Then the optimizations kick in. There is a <em>denominations</em> array, which has a list of coin values, from 1 dollar, a quarter, a dime, a nickel and finally a penny.</p>
<pre class="brush: java; title: ; notranslate">
int[] denominations = { 100, 25, 10, 5, 1 };
</pre>
<p>One of the original requirements of the program was that the amount of coins needed must be in their proper plurality. I can do this easily by having a two dimensional array of strings that store both forms of each word. You might ask, why not just attach an extra <em>s</em> to the end if it&#8217;s plural? Well, <em>penny</em> doesn&#8217;t turn into <em>pennys</em>.</p>
<pre class="brush: java; title: ; notranslate">
String[][] terms = { { &quot;dollar&quot;, &quot;dollars&quot; },
        { &quot;quarter&quot;, &quot;quarters&quot; }, { &quot;dime&quot;, &quot;dimes&quot; },
        { &quot;nickle&quot;, &quot;nickles&quot; }, { &quot;penny&quot;, &quot;pennies&quot; } };
</pre>
<p>The program will spit out values for each of the denominations listed, so it will contains dollars, quarters and so on and it&#8217;s store in this values array.</p>
<pre class="brush: java; title: ; notranslate">
int[] values = new int[denominations.length];
</pre>
<p>I use a rolling total to keep track of how much change is left over still.</p>
<pre class="brush: java; title: ; notranslate">
int rolling = cents;
</pre>
<p>The magic happens in the for-loop. It&#8217;s completely standard, initialized to 0, counting towards the length of the denominations array and incrementing by 1.</p>
<pre class="brush: java; title: ; notranslate">
for (int i = 0; i &lt; denominations.length; i++) {
</pre>
<p>The calculations happen in the next section. Basically, the denomination integer pulls the proper value from the denominations array. Then, the value in the values array is set to the <em>integer division</em> of the rolling total and current denomination. Finally, the rolling value is truncated by the denomination by <em>modulus</em>.</p>
<pre class="brush: java; title: ; notranslate">
    int denomination = denominations[i];
    values[i] = (rolling / denomination);
    rolling = rolling % denomination;
</pre>
<p>To pick the proper singular or plural, the value is checked against being 1. Keep in mind that values of fractions are indeed plural. <em>You have .1 dollars, e.g. ten cents, or a dime.</em></p>
<pre class="brush: java; title: ; notranslate">
    String term = (values[i] == 1 ? terms[i][0] : terms[i][1]);
</pre>
<p>Finally, there is the printing logic which always gets in the way. I certainly wish there was a better way, but this was the best I found. Basically, by counting up until the last value, I print without a new line the value and then the matching proper term, and when it reaches the last value, I print an <em>and</em>, value, term and finally a period.</p>
<pre class="brush: java; title: ; notranslate">
    if (i &lt; (denominations.length - 1)) {
        System.out.print(values[i] + &quot; &quot; + term + &quot; &quot;);
    } else {
        System.out.println(&quot;and &quot; + values[i] + &quot; &quot; + term);
    }
</pre>
<p>Here&#8217;s a short sample run with different amounts of cents.</p>
<pre>
Ryans-MacBook-Air:APCS3 ryanrampersad$ java CorrectChange
Enter some amount in cents: 
119
Your change is: 1 dollar 0 quarters 1 dime 1 nickle and 4 pennies.
Ryans-MacBook-Air:APCS3 ryanrampersad$ java CorrectChange
Enter some amount in cents: 
169
Your change is: 1 dollar 2 quarters 1 dime 1 nickle and 4 pennies.
Ryans-MacBook-Air:APCS3 ryanrampersad$ 
</pre>
<p>I remember when I wrote this program four years ago. This program is 35 lives with a bunch of whitespace. My code from youth was probably more like 70 lines. As you code, you mature. As you read others&#8217; code, you mature too. Experimenting is the best way to grow. You can of course <a href="http://blog.ryanrampersad.com/wp-content/uploads/2011/08/CorrectChange.txt">download the full source code</a>.</p>
<p class="signoff"><em>Happy counting.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2011/11/30/correct-change-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>★ How to Write byte[] to a File in Java</title>
		<link>http://blog.ryanrampersad.com/2011/10/20/how-to-write-byte-to-a-file-in-java/</link>
		<comments>http://blog.ryanrampersad.com/2011/10/20/how-to-write-byte-to-a-file-in-java/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 17:23:20 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[bytes]]></category>
		<category><![CDATA[files]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4092</guid>
		<description><![CDATA[For a little project I needed to save lots of index positions from many arrays to file. They were numbers, so they were basically ints, but instead of four bytes, I could get away with a single byte, saving on memory. It was more efficient too save bytes directly instead of parsing strings of integers [...]]]></description>
			<content:encoded><![CDATA[<p>For a little project I needed to save lots of index positions from many arrays to file. They were numbers, so they were basically ints, but instead of four bytes, I could get away with a single byte, saving on memory. It was more efficient too save bytes directly instead of parsing strings of integers out later.</p>
<p>I have an array of bytes which comprise my data, then I have an <code>OutputStream</code> with an attached data container file created by a <code>FileOutputStream</code>. All it takes after that is a <code>.write</code> with the data array and finally a <code>.close</code> to close the file stream.</p>
<pre class="brush: java; title: ; notranslate">
public static void main(String[] args) throws Exception {
 byte[] data = {-1, 0, 0, 1, -1, 0, 1, 1, 1, 0, -1, -1};
 OutputStream out = new FileOutputStream(&quot;test.txt&quot;);
 out.write(bytes);
 out.close();
}
</pre>
<p>There are a couple things to keep in mind though. Since this uses the file system, this will may throw exceptions which means you need to catch them. I used <code>throws Exception</code> but you may want to use a try/catch series.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2011/10/20/how-to-write-byte-to-a-file-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>★ Multiplication Table in Java</title>
		<link>http://blog.ryanrampersad.com/2011/10/17/multiplication-table-in-java/</link>
		<comments>http://blog.ryanrampersad.com/2011/10/17/multiplication-table-in-java/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 17:08:40 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[multiplication]]></category>
		<category><![CDATA[table]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4504</guid>
		<description><![CDATA[One of my friends came to me the other day asking I could help out with the logic for printing a multiplication table out. Go back to those days in second grade when you were learning all the combinations of small numbers from 1 to 12 for multiplication products. That was a long time ago. [...]]]></description>
			<content:encoded><![CDATA[<p>One of my friends came to me the other day asking I could help out with the logic for printing a multiplication table out. Go back to those days in second grade when you were learning all the combinations of small numbers from 1 to 12 for multiplication products. That was a long time ago. Quick, what&#8217;s <em>7 times 9</em>?</p>
<p>Anyway, printing out a multiplication table like this one isn&#8217;t too hard.</p>
<blockquote>
<pre>
x	1	2	3	4	5	
1	1	2	3	4	5	
2	2	4	6	8	10	
3	3	6	9	12	15	
4	4	8	12	16	20	
5	5	10	15	20	25	
</pre>
</blockquote>
<p>Let&#8217;s think of the logic behind this. In the first row, we have the <em>X</em> value, so it counts from 1 up to X<sub>max</sub>. In the first column, we have the <em>Y</em> value, so it counts from 1 up to Y<sub>max</sub>. It is duly noted that the table only has a <em>X</em> listed, but that&#8217;s for simplicity, though there is a X and a Y, horizontal and vertical.</p>
<p>In the next row, where X is 1 and Y is 1, we have simple multiplication, 1 times 1, so the value is 1. In the second row and column we have the same numbers as the first row and column because of that <em>by 1 multiplication</em>. Now, we&#8217;ll take a look at some code.</p>
<pre class="brush: java; title: ; notranslate">
public static String getNumber(int i, int j) {
	int value = i * j;
	
	if ( i == 0 ) {
		value = (i+1) * j;
	} else if ( j == 0 ) {
		value = i * (j+1);
	}
	
	if ( i == 0 &amp;&amp; j == 0 ) return &quot;x&quot;;
	else return value+&quot;&quot;;
}
</pre>
<p>So let&#8217;s break this down. You have a <code>value</code> which is obvious in its purpose: it&#8217;s the resultant multiplication of some row and some column. Then things get complicated. Since we&#8217;re, what? Either computer scientists or insane, we count from <em>zero</em>. Counting from zero makes us think about out logic.</p>
<p>If you&#8217;re in the first row, you&#8217;ll need to print out what would be the next row. What? Imagine you&#8217;re making a table for 5 by 5. You&#8217;ll need <nobr><code>1 2 3 4 5</code></nobr>. How do you get that? You multiply the column value by 1. But you only want this to happen naturally in the first row (which is actually the zeroth row by our zero-count). And we&#8217;ll need the same for the columns going down. So that&#8217;s what happens in that first if-else-if stack. If <code>i</code> or <code>j</code> is 0, then it will be temporarily incremented by 1 and it&#8217;ll print out the proper rows.</p>
<p>The the if-else stack at the end of this statement is pretty easy too. The if-statement checks to see if <code>i == 0 &#038;&#038; j == 0</code>, or if i and j are equal to zero, it will return the <em>X</em> that is the first value in the table. If that condition isn&#8217;t true, then it&#8217;ll print out either the regular <code>i * j</code> value or the specialized first row/column value.</p>
<p>Now we&#8217;ll need a loop.</p>
<pre class="brush: java; title: ; notranslate">
	for (int i = 0; i &lt;= height; i++) {
		for (int j = 0; j &lt;= width; j++) {
			System.out.print( getNumber(i, j) + &quot;\t&quot; );
		}
		System.out.println(&quot;&quot;);
	}
</pre>
<p>This is a nested for-loop. The outside loop will handle the rows (e.g. the height) and the inner loop will handle the columns (e.g. the width). There is a method call to the getNumber with arguments i and j, and a printout that has getNumber and appends a <em>tab character</em> at the end. Finally, in the outside loop, when the inner loop is done running, a newline is printed so that the next row will begin to form.</p>
<p>The logic for this type of program is an exercise in looping and conditional logic with index values. You can grab <a href="http://blog.ryanrampersad.com/wp-content/uploads/2011/10/MultiplicationTable.txt">the source code here</a>.</p>
<p class="signoff"><em>Happy multiplying.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2011/10/17/multiplication-table-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>★ Find the Index of Largest Array Element in Java</title>
		<link>http://blog.ryanrampersad.com/2011/08/13/find-the-index-of-largest-array-element-in-java/</link>
		<comments>http://blog.ryanrampersad.com/2011/08/13/find-the-index-of-largest-array-element-in-java/#comments</comments>
		<pubDate>Sat, 13 Aug 2011 17:15:58 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[tip]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=4181</guid>
		<description><![CDATA[Finding the index of the largest element in an array is relatively easy. I remember seeing a couple free response questions in the AP Computer Science Exam that involved this type of problem too, so it&#8217;s good to know. You&#8217;ll need an array full of numbers, those could be integers, doubles, longs, whatever, as long [...]]]></description>
			<content:encoded><![CDATA[<p>Finding the index of the largest element in an array is relatively easy. I remember seeing a couple free response questions in the AP Computer Science Exam that involved this type of problem too, so it&#8217;s good to know.</p>
<p>You&#8217;ll need an array full of numbers, those could be integers, doubles, longs, whatever, as long as it is comprised of a number. My solution uses two data keeping variables, <code>largest</code> and <code>index</code>. The <code>largest</code> variable will keep track of the biggest value in the array while the <code>index</code> variable keeps track of where the largest value was found.</p>
<p>Optionally, I like to set the <code>largest</code> and <code>index</code> variables before I start any testing. <code>largest</code> is set to <code>array[0]</code> and <code>index</code> is set to <code>0</code> so that we can skip that initial value.</p>
<pre class="brush: java; title: ; notranslate">
int[] array = {29, 42, 1, 32, 44, 49, 0, 13, 43, 30};
int largest = array[0], index = 0;
for (int i = 1; i &lt; array.length; i++) {
  if ( array[i] &gt; largest ) {
      largest = array[i];
      index = i;
   }
}
</pre>
<p>This will set <code>index</code> to 5 because 49 is the largest in the array.</p>
<p>If there had been two instances of <em>49</em> in the array, which would have been returned? The first one as the code stands. To change it, one would simply have to change the conditional from <em>greater than</em> to <em>equals or greater than</em>.</p>
<pre class="brush: java; title: ; notranslate">
int[] array = {29, 42, 1, 32, 44, 49, 0, 13, 43, 49};
int largest = array[0], index = 0;
for (int i = 1; i &lt; array.length; i++) {
  if ( array[i] &gt;= largest ) {
      largest = array[i];
      index = i;
   }
}
</pre>
<p>This would set <code>index</code> to 9 because 49 is the <em>last</em> largest in the array.</p>
<p>Wouldn&#8217;t it be nice of Java had a method that did this for you? Like: <code>Arrays.largest</code> or <code>Arrays.smallest</code> which would work for primitive numeric values. Simple and obvious.</p>
<p class="signoff"><em>Happy indexing.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2011/08/13/find-the-index-of-largest-array-element-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>★ Java &#8211; Failed to download required installation files</title>
		<link>http://blog.ryanrampersad.com/2011/07/04/java-failed-to-download-required-installation-files/</link>
		<comments>http://blog.ryanrampersad.com/2011/07/04/java-failed-to-download-required-installation-files/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 17:29:41 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[error]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=3471</guid>
		<description><![CDATA[Have you ever been watching a movie and Windows will throw its UAC screen up busting you out of full-screen during your movie alerting you that Java has an update? It&#8217;s happened to me. So you relent and you take it upon yourself to be diligent and actually update Java, you tell UAC it&#8217;s fine [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever been watching a movie and Windows will throw its UAC screen up busting you out of full-screen during your movie alerting you that <em>Java has an update</em>? It&#8217;s happened to me.</p>
<p>So you relent and you take it upon yourself to be diligent and actually update Java, you tell UAC it&#8217;s fine and to proceed. And then the Java installer comes up asking you to accept some terms of service before the update is downloaded and installed. But then. This.</p>
<p><a href="http://blog.ryanrampersad.com/wp-content/uploads/2011/06/java-failed-to-download.png"><img src="http://blog.ryanrampersad.com/wp-content/uploads/2011/06/java-failed-to-download.png" alt="Java - Failed to download required installation files" title="Java - Failed to download required installation files" width="390" height="202" class="aligncenter size-full wp-image-3472" /></a></p>
<p>Now what? What can you do? The little Java icon in the task tray is gone and it won&#8217;t pop up again for a few hours. There is no solution to this problem, except for <a href="http://www.java.com/en/download/">downloading the new version of Java directly</a>. Or you can wait again until the prompt comes back up. That&#8217;ll work too.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2011/07/04/java-failed-to-download-required-installation-files/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>★ HashMap Iteration &#8211; Java</title>
		<link>http://blog.ryanrampersad.com/2011/05/26/hashmap-iteration-java/</link>
		<comments>http://blog.ryanrampersad.com/2011/05/26/hashmap-iteration-java/#comments</comments>
		<pubDate>Thu, 26 May 2011 18:55:44 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[unified]]></category>

		<guid isPermaLink="false">http://blog.ryanrampersad.com/?p=2879</guid>
		<description><![CDATA[I needed to iterate a HashMap in Java. I can do it effortlessly in PHP with just a regular array or in JavaScript with an object literal. In Java though, the process is a little bit more obtuse. I had a special case &#8211; needing both the key and the value at the same time. [...]]]></description>
			<content:encoded><![CDATA[<p>I needed to iterate a HashMap in Java. I can do it effortlessly in PHP with just a regular array or in JavaScript with an object literal. In Java though, the process is a little bit more obtuse.</p>
<p>I had a special case &#8211; needing both the key and the value at the same time. Let&#8217;s go with one or the other for right now. Let&#8217;s establish our map.</p>
<pre class="brush: java; title: ; notranslate">
HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
map.add(&quot;Hello&quot;, &quot;world&quot;);
map.add(&quot;Ryan&quot;, &quot;rampersad&quot;);
</pre>
<p>That&#8217;s our example map. It doesn&#8217;t really matter what the contents are, but it&#8217;s example.</p>
<p>Now, let&#8217;s loop over the keys.</p>
<pre class="brush: java; title: ; notranslate">
Iterator it = map.keySet().iterator();
while (it.hasNext()) System.out.println( it.next() );
</pre>
<p>This will print out <em>Hello</em> and <em>Ryan</em>. Those are the keys of the values in the Hash Map.</p>
<p>Now let&#8217;s loop over the values.</p>
<pre class="brush: java; title: ; notranslate">
Iterator it = map.values().iterator();
while (it.hasNext()) System.out.println( it.next() );
</pre>
<p>This will print out <em>world</em> and <em>rampersad</em>. Those are the values.</p>
<p>Finally, the most interesting. To get the value and the key at the same time, a special Map Entry object can be made with an entry set.</p>
<pre class="brush: java; title: ; notranslate">
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
  Map.Entry&lt;String, String&gt; kv = it.next();
  System.out.println(kv.getKey() + &quot;=&quot; + kv.getValue());
}
</pre>
<p>This code prints <em>Hello=world</em> and <em>Ryan=rampersad</em>.<br />
This is new. First, we call <code>entrySet</code> to get the special set of key-value pairs. Then in the loop itself we use a special <code>Map.Entry</code> object with parameters of <code>String, String</code>, because that&#8217;s how our map is made, and set it to <code>it.next</code>. That enables use to call for the key and the value.</p>
<p>I hate <code>while</code> loops so I suggest this format instead.</p>
<pre class="brush: java; title: ; notranslate">
for (Map.Entry&lt;String, String&gt; kv: map.entrySet()) {
  System.out.println(kv.getKey() + &quot;=&quot; + kv.getValue());
}
</pre>
<p>The beauty of this is that there is no <code>Map.Entry</code> object being declared inside the actual loop, instead it&#8217;s made it its header. All the cleaner.</p>
<p>Getting a key-value pair from a HashMap, the point of HashMap, I think, is slightly convoluted but nothing hard.</p>
<p>Happy mapping.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ryanrampersad.com/2011/05/26/hashmap-iteration-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

