04.04.2013 Views

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 6-25. Auto Layout sketch<br />

This sketch utilizes a fair amount of variables, so it might look a bit confusing. Definitely<br />

take your time going through it. I think the auto-layout feature is worth taking the time to<br />

underst<strong>and</strong>, as this type of process is quite valuable when you’re doing visual stuff. You’ll<br />

also notice that I initialized a second local variable (j) in the for loop head, which I use to<br />

cycle through the caps[] array. There is also a conditional statement that keeps resetting<br />

j to 0, ensuring that the index of the array stays within bounds. Remember, arrays are<br />

zero-indexed—so if you have three items in an array, the last index number will be 2, or<br />

array.length-1. If you make a request to access an index position in an array that doesn’t<br />

exist, you’ll get an error. This is a very common mistake, <strong>and</strong> usually pretty easily (<strong>and</strong><br />

happily) resolved.<br />

I also snuck in some formatting that hopefully will look quite suspect: if (j>2) j=0;. This<br />

is actually a normal conditional statement that I put on one line, leaving off the curly<br />

braces. Yes, this is legal code, as long as you only use one statement in the block of the<br />

code (between where the curly braces would have been). You can even use an else statement<br />

after the if block—but again, only one line of code will be recognized by the structure<br />

if you don’t include curly braces. You’ll also get a compiler error if you include the<br />

else <strong>and</strong> have more than one line in the if block. Regardless of how you format your if<br />

statement, it makes no difference whether you put it on one line or skip a line between<br />

each part (at least to the compiler). Whitespace is ignored by the compiler, except if it’s<br />

between quotation marks, which it then sees as character spaces. In the next examples, the<br />

first two snippets works fine, but the last two don’t work.<br />

Here’s Example 1, which works:<br />

for (int i =0; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!