Help with Java Code?

Hi! I was hoping for some Java enthusiasts to help my illogical brain solve this trivial code… I was watching a Youtube video on some Processing tutorials… Processing as far as I understand is an IDE where you use the Java language primarily to draw on the screen.

The video went on to explain how to move an ellipse from left to right, with a mouse click event when the user clicks the mouse:

//Variables
boolean going = false;
float x = 0;

//The Window Setup
void setup() {
size(700, 400);
}

//The Drawing procedure
void draw() {
background(0);
fill(255);

ellipse(x, 200, 50, 50);
if (going) {
x = x + 1;
}
}

//Mouse click Event
void mousePressed() {
if (going) {
going = false;
}else going = true;

}

The relevant piece of code where I am stuck is the following:

A):
void mousePressed() {
if (going) {
going = false;
}else going = true;
}

The code above works perfectly, but I thought the following code would make sense:

B):
void mousePressed() {
if (going) {
going = true;
}else going = false;
}

Since the initial value of going is false, in my version of the code(B), the “going” variable will become true when the mousePressed() event is triggered (click the mouse), but when I run this code, the ellipse does not move on the screen as intended.

It only moves when (A) is executed, instead of (B). As you can see, all I am changing is the value of going. Anyone who can reply to this? Apologies if my English does not make sense. Thank you :slight_smile:

On another note if I implement this following code:

void mousePressed() {
if (going == false) { <---------------------
going = true;
}else going = false;

Then, the ellipse moves as intended, the same way as code (B).

In the code, the value of going is not changed at all.

The stuff in the block after if (going) only runs when going is true
so when that is the case, going = true sets going to be true (but it was already true, so it did not change).

Similarly, the else-block runs when going is false
so when that is the case, going = false sets going to false (but it was already false, so it didn’t change).

If you just want to switch the boolean variable from true to false or false to true, another way to do that is

going = !going; 
1 Like

I am trying to make sense of this and eventually, I will, I hope. I was confused since the initial value that the person in the video gave to “going” was false. So you are saying that it needs to evaluate to TRUE…? It cannot start the code by evaluating to FALSE?

I think I have answered my own question with your help. I was under the impression that even if a conditional statement is False, the code inside that conditional would execute, based on that “If this is False, the execute” thinking in my mind… When in reality, the code inside an if statement will ever only execute if the condition evaluates to true: “If this is true, then execute” otherwise it will skip that code snippet and jump to the next line.

1 Like