This site requires JavaScript, please enable it in your browser!
Greenfoot back
new2programming
new2programming wrote ...

2013/4/18

How to use type boolean variable?

new2programming new2programming

2013/4/18

#
Hey guys, I need to learn how to use boolean in my work. But I just can't seem to figure out how it works. I know that the boolean variable determines a value if it is true or false only. But I don't know how to write it down or how it's use.
1
2
3
4
5
6
7
8
9
10
11
boolean checkTreeRight = false;
         
        checkTreeRight = treeRight;
            checkTreeRight = true;
            turnLeft();
            move();
            turnLeft();
            checkTreeRight = false;
            turnRight();
            move();
            turnRight();
Can someone explain to me how this works? I mean how does the program know what the variable means to be able to determine if its true or false? And if I'm completely wrong, can someone run through the basics of the boolean variable for me?
davmac davmac

2013/4/18

#
A boolean variable is just like any other variable (like an 'int' variable). Except whereas an int variable can hold a lot of different values - 0, 1, 2, 3, 1000, -1, etc - a boolean variable can only have two possible values, 'true' and 'false'. There's nothing magic about them otherwise - they work exactly as other variables do. Because the value of a boolean is already true or false, you don't need to compare them in 'if' statements, i.e. instead of writing:
1
if (myBooleanVar == true) ...
you can write:
1
if (myBooleanVar) ...
I mean how does the program know what the variable means to be able to determine if its true or false?
The program doesn't know what the variable means. The only way your program can behave differently depending on the value of a variable is to use the variable (eg use it an "if" statement as per example above). I'm guessing that your 'turnLeft', 'turnRight' and 'move' methods respond to the value of the checkTreeRight variable in exactly this way.
You need to login to post a reply.