We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › if else in 1 line possible
Page Index Toggle Pages: 1
if else in 1 line possible? (Read 769 times)
if else in 1 line possible?
Jan 5th, 2010, 3:06pm
 
I was wondering,

if(g[i] == true)stroke(0);

Is it possible to have the else also in that line?
Re: if else in 1 line possible?
Reply #1 - Jan 5th, 2010, 3:19pm
 
Yes:

if ( g[i] ) stroke(0); else stroke(255);

but is it really necessary ?
Re: if else in 1 line possible?
Reply #2 - Jan 5th, 2010, 4:16pm
 
The compiler doesn't care about line breaks (new lines) - they are essentially the same as a space, except in special circumstances such as inside a "quoted string", and the end of line marks the end of a line comment (starting with "//").

The semicolon (";") is the statement separator.

It is generally a Good Idea to lay out your code in a clear-to-follow style, and not try to put too much all in a small visual space on the page.

Indentation, spacing between operators (such as "=" and "+"), and most of all consistency with your layout make it easier to read and understand, which ultimately helps you write better code and makes it easier for you to go back to it later for maintenance and/or enhancement.

In cases where you want to do something with a choice between two values, you can use the "ternary operator".

Many explanations can be found online, such as Java Term of the Week: Ternary Operator

In your case, you might try something like this:

Code:
stroke( g[i] ? 0 : 255 ); 



The "magic numbers" here (0 and 255) might make better sense if you put them in variables (or constants), eg

Code:
static final int G_ON_STROKE = 0;
static final int G_OFF_STROKE = 255;

stroke( g[i] ? G_ON_STROKE : G_OFF_STROKE );


I don't know what your g[] array values mean; hopefully you can come up with better names for the constants!  Wink

-spxl
Re: if else in 1 line possible?
Reply #3 - Jan 5th, 2010, 4:18pm
 
sometimes i prefer to keep things on 1 line but no it's not really necessary.

and thx subpixel.
Page Index Toggle Pages: 1