We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have this code:
int[] colors(String shapeShade){
if(shapeShade == "red"){
int[] colorArray = {255,0,0};
}
else if(shapeShade == "blue"){
int[] colorArray = {0,0,255};
}
else if(shapeShade == "green"){
int[] colorArray = {0,255,0};
}
}
return colorArray;
}
And it seems it should work, but it keeps telling me "expected EOF", how do I return this array? If it matters, I'm returning this to an array of the same size in the constructor of a class.
Answers
http://forum.processing.org/two/discussion/8045/how-to-format-code-and-text
int[] colorArray = {255, 0, 0};
.if
scoped blocks.return colorArray;
, variable colorArray doesn't exist anymore.==
equality operator.Hmm... seems like you already had problems w/ scoping before: :-\"
http://forum.processing.org/two/discussion/11221/class-not-working-what-am-i-doing-wrong
The function is also closed before the return statement: check your {braces}...
I remember being bitten by the issue @GoToLoop refers to. Since colorArray gets declared only inside conditions there's a risk that it never gets declared. So declare the empty variable before the conditions, rather than repeatedly inside them... You could even remove a condition altogether: e.g. set its value to red and then override it when appropriate.
I don't get what you meant by "risk". Declarations always overshadow other variables declared in outer scopes if they happen to have the same name until the end of the inner scope.
do all { } automatically make a new scope?
like for and if () { } ?
Yes
thanks
@GoToLoop: my description wasn't meant to be overly technical, but the way I always thought about this situation was that I may know that one of the three conditions will always return true, so there should be a value to return, but the interpreter can't know this so reports it as an error...
I guess on a technical level it simply can't find the variable declared in the same scope?
}
curly brace.return
statement.==
operator.""
1, like "red", "blue" or "green". :PBe aware that any declaration inside
for
's parens is also its own separate scope,apart from its
{}
's scope.For example, the following code won't compile due the "inexistence" of variable step,
since it doesn't exist inside
for ()
parens's scope: :-BSo if I declare the array like
int[] colorArray = new int[3];
then can I assign data later using
colorArray = {255,0,0};
The answer is: "Yes & No"! @-)
=
assign operator, the old stored value is discarded.int[] colorArray = new int[3];
int[] colorArray;
new int[]
array assignment down the road after all.{ 255, 0, 0 }
int[] colorArray = { 255, 0, 0 };
colorArray = new int[] { 255, 0, 0 };
P.S.: Processing got a pseudo type called
color
which is the same asint
. ;;)https://processing.org/reference/color_datatype.html