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.

Assignment operators<br />

The only other operators you need to look at for now are used for assignment operations.<br />

The simplest assignment operation just uses the = operator. For example, to assign the<br />

value 55 to the int variable speed, you’d simply write the following:<br />

int speed = 55;<br />

Again, the = sign is used for assignment, not equality. When you test for equality in<br />

<strong>Processing</strong> <strong>and</strong> Java, instead of writing if(speed=55), you need to write if(speed==55).<br />

The first way actually assigns the value 55 to speed; the second way tests if speed is actually<br />

equal to 55. Using the single-equal sign when testing for equality is a very common<br />

mistake new coders make. We’ve been conditioned to think of equality as =, not ==, so it<br />

makes sense that new coders find it confusing.<br />

When I write an assignment statement, for example<br />

x = 4;<br />

I am assigning 4 to x. So now the value of x evaluates to 4. Let’s say I want to add 3 to x—<br />

I could write x + 3, right? Let’s try it.<br />

Write the following two lines of code in <strong>Processing</strong> <strong>and</strong> click run.<br />

int x = 4;<br />

x + 3;<br />

Surprised you got an assignment error? It’s because you’re adding 3 to x, but not assigning<br />

the solution anywhere. Remember that computers are really dumb. If they can’t put the<br />

value anywhere, they don’t know what to do. Fortunately, the <strong>Processing</strong> compiler sends<br />

out a compiler error letting you know this.<br />

You can fix the preceding assignment in a couple of ways—but the easiest way to add 3 to<br />

x, <strong>and</strong> then assign the value back to x, is as follows:<br />

x = x + 3;<br />

Now this may look a little odd, having something assigned to itself. But reading the expression<br />

in English helps: add the value of x <strong>and</strong> 3 <strong>and</strong> then assign that value to x. Assignment<br />

operations happen from right to left. It may take a little time playing with this to get it<br />

clear in your brain. These operations work the same way for the other mathematical operators<br />

as well. Here’s a division example:<br />

float y = 10.4;<br />

// divide by 1.25<br />

y = y / 1.25;<br />

CODE GRAMMAR 101<br />

75<br />

3

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

Saved successfully!

Ooh no, something went wrong!