Error unexpected token: void

Hello, I’m trying to learn processing but I have an error with my code. Here is my code :

void step() {
  float x;
  float y;
  float r = random(1);
  
  if (r < 0.4) {
    x++;
  } else if (r < 0.6) {
    x--;
  } else if (r < 0.8) {
    y++;
  } else { 
    y--;
  }
}

My error :
“The local variable x may not have been initialized”

Thank you for helping me !

1 Like

just say float x=0 ; in the line you already have

Is this your entire sketch by the way?

The function step wouldn’t run on its own.

You should have a function setup and draw as well. Call step() from draw().

Please look on the website tutorials section, first three text tutorials

1 Like

It’s not my entire sketch. I’m learning with Daniel Shiffman’s book.

1 Like

hi,
-a- please format your code using the </> Preformatted text button

-b- also post code as short as possible just to show your problem
but complete as in we can copy / paste it into the PDE and it runs…


a running version would be

one cycle

void setup() {
  step();
}

float x;
float y;

void step() {
  float r = random(1);
  print("r "+nf(r,0,2)+" x "+x+" y "+y);
  if      (r < 0.4)    x++;
  else if (r < 0.6)    x--;
  else if (r < 0.8)    y++;
  else if (r > 0.8)    y--;
  println(" now: x "+x+" y "+y);
}

or conti

void setup() {}
void draw() {
  step();
}

float x;
float y;

void step() {
  float r = random(1);
  print("r "+nf(r,0,2)+" x "+x+" y "+y);
  if      (r < 0.4)    x++;
  else if (r < 0.6)    x--;
  else if (r < 0.8)    y++;
  else if (r > 0.8)    y--;
  println(" now: x "+x+" y "+y);
}

2 Likes

Can you more explain the code, please ? What’s the difference between “print” and “println” ?

println makes a new line / line break after the text, print doesn’t. It stays in the same line

With a small adjustment we can see it more graphic :stuck_out_tongue:

PVector walker;

void setup() {size(displayWidth,displayHeight);}
void draw() {
  walker = step();
  fill(random(255),120);
  translate(width/2,height/2);
  ellipse(walker.x,walker.y,10,10);
}

float x;
float y;

PVector step() {
  float r = random(1);
  print("r "+nf(r,0,2)+" x "+x+" y "+y);
  if      (r < 0.4)    x++;
  else if (r < 0.6)    x--;
  else if (r < 0.8)    y++;
  else if (r > 0.8)    y--;
  println(" now: x "+x+" y "+y);
  return new PVector(x,y);
}
1 Like