Ok so lets say I have boolean x = false. If I have a loop that says while (!x) does this mean while x is NOT false (true) or while x is NOT true (false)?
EDIT:
Ok I'm a bit confused, I think Im getting different answers. So if I have
int x=0;
boolean add1=false;
while (!add1){
x=1;
}
What is the final value of x in this case?
x=false;
while (!x)
substituting the value of x we have
while(!false)
Now ! is the logical complement operator which inverts the value of a boolean so we get
while(true)
So we keep looping till x is false or till !x is true.
Note that the value of the variable can change in the body of the loop causing the looping to break. Consider a typical search program which uses a boolean variable called found:
found = false; // initialize found to false.
while(!found) { // keep looping till key is not found.
...
if(key is found) {
found = true; // key found...make found true.
}
}
UPDATE:
In your updated question add1 is false initially so !add1 is true so we enter the while loop and change x to 1. Since the value of add1 does not change in the loop and there are no break and return you keep looping infinitely.
The loop will repeat as long as !x is true. In other words, it will repeat as long as x is false.
A boolean condition is always checked for being true. So while (!x) means while x is not true, i.e. while x is false.
Update: The code you posted is an infinite loop since !add1 evaluates to true and this is never changed within the loop.
I feel nobody really (tried to) explain, what it means.
while (!x) does not really mean much. It is only a few instructions for the computer to do. It does not mean things like do stuff while x is true or false or whatever. !x is an expression and in the case that x = false, this expression yields true. The computer actually calculates true by applying ! on the value of x: false.
while(!x) does not mean "run when x equals false." It means something like "run if inverting the truth value of variable x yields true." From experience we know (or learn) that it is about the same as "run only when x equals false". Just like while (!(x && !x)) means(?) "run always". You can see this by trying all possible values of x and remembering those who will make the expression equal true. Some day you will just know what it 'means'.
What it does, how it works, is not what it means, right?
The loop will continue to iterate so long as x = false. If x = true the loop will end.
Let's replace x with red sky. While the sky is not red, red sky = false will evaluate as true.
Asking repeatedly whether the value red sky is not true (as long as the sky stays blue, of course) will cause the loop to repeat.
I think you have a code smell here.
I prefer to have simple while conditions, to keep the code readable. So if you end with a piece of logic that looks like:
boolean is_something = false;
while (!is_something) {
...
}
maybe it's better to reverse both the meaning of the variable and its default value, to get rid of the negation in the while condition:
boolean is_not_something = true;
while (is_not_something) {
...
}
Please note that this is a very general example. Often you don't need to have an explicit negation in the variable name. If you have a variable called is_empty, the opposite doesn't have to be called is_not_empty, it can be called is_full.
while(!add1) runs if add1 is false. Since add1 is always false, x will always equal 1.
Related
I'm trying to make 'The Game of Life' in Java. I made a 2d matrix and filled it with boolean values.
Now I'm trying to count the boolean values of adjacent cells that are true, but when I use =, I get all of the cells surrounding it (eg: a cell in the middle gives 8, a cell on a corner gives 3) and when I use ==, I just get all 0's.
Example if statement (first one works, second doesn't work):
if(!celloc.equals("URC") && !celloc.equals("RightB") && !celloc.equals("LRC")) {
if(current[i][j+1] = true) {
life++; // right
}}
A single "=" is for assignment, use "==" when testing for equivalency. Also, if "current[i][j+1]" is a boolean you can simply type:
if(current[i][j+1]) {
to test if that value is true. You may be getting 0 because you may not be getting to that if statement. Try adding some output to see if your first if statement is ever actually true.
In my quiz game on the very end of a level I have to check some conditions, 4 of them. During the game I add +1 to an integer variable, 4 variables. On the end of the level I sum these values to another integer, activeButtonsTotal. And I set 4 boolean values to true or false. So, I need to check 2 conditions four times: if it's my boolean is false AND if my activeButtonsTotal is equal to 16 and if it is to set one of my buttons to Enabled, and this same thing for the next boolean and activeButtonsTotal, and 4 times like this. I need to go through all 4 of them. I tried with if statements, and else if but no luck.
boolean columnACorrecct, columnBCorrect, columnCCorrect, columnDCorrect;
activeButtonsTotal = activeButtonsA+activeButtonsB+activeButtonsC+activeButtonsD;
if((columnACorrect=false) && (activeButtonsTotal==16)){
columnA.setEnabled(true);
}
if((columnBCorrect=false) && (activeButtonsTotal==16)){
columnB.setEnabled(true);
}
if((columnCCorrect=false) && (activeButtonsTotal==16)){
columnC.setEnabled(true);
}
if((columnDCorrect=false) && (activeButtonsTotal==16)){
columnD.setEnabled(true);
}
im not sure that i follow all your logic, but your "if" statements all are missing an equal sign. You said you have to compare if your boolean is false, AND the number, but you are assigning "False" inside the condition. you need "==".
I would do:
if(activeButtonsTotal==16)
{
columnA.setEnabled(!columnACorrect);
columnB.setEnabled(!columnBCorrect);
columnC.setEnabled(!columnCCorrect);
columnD.setEnabled(!columnDCorrect);
}
I would do something like that:
columnA.setEnabled(!columnACorrect && activeButtonsTotal==16);
columnB.setEnabled(!columnBCorrect && activeButtonsTotal==16);
columnC.setEnabled(!columnCCorrect && activeButtonsTotal==16);
columnD.setEnabled(!columnDCorrect && activeButtonsTotal==16);
You are assigning your boolean variable to false every time you try to check a condition.
This will result in the condition to be false and will never run the code within the block.
To check for equality, use ==;
columnACorrect==false
columnBCorrect==false
columnCCorrect==false
columnDCorrect==false
But I would recommend using:
!columnACorrect
!columnBCorrect
!columnCCorrect
!columnDCorrect
It does the same thing. The 2nd option is more preferable.
I'm studying for the OCA Java SE7 Associate exam. One of my practice exam questions had the following code snippets:
boolean flag = true;
if (flag = false) {
System.out.println("1");
}
else if (flag) {
System.out.println("2");
}
else if (!flag) {
System.out.println("3");
}
else
System.out.println("4");
Notice the if (flag = false) conditional. The question asked what the output of this snippet would be. All the numbers were provided as answer choices and then there was a choice that said "compiler error," which is what I selected. I was wrong. The output would be 3. I tested in Eclipse and it also came back with 3.
I then tested with
int x = 3;
int y = 1;
if (x = y) {
// whatever
}
and, of course, got an error.
Why can the flag be changed from true to false inside the if-statement, but the value of x can't be changed in the similar scenario? Is it because flag is a boolean type and x is type int? I Googled this, but was unable to find anything.
Because the assignment of x = y doesn't equate to a boolean evaluation.
if is expecting the result of the operation to give either a true or false return.
Something like if ((x = y) == y) would work (the evaluation would return true)
flag = false is an assignment, so it is carried out. After the assignment on the first if, it evaluates to false because it was just set to it. For equality it should have been flag == false, but since it was an assignment, the top if was evaluated to false, and since it was changed to false, when you get to !flag, that passes because flag is no longer true, and it prints 3.
You got an error with if(x = y) because after the assignment, the value couldn't be evaluated as a boolean outcome whereas if(flag = false) can evaluate to boolean after the assignment.
The big thing to remember about high-level languages is that it takes more than one low-level statement to perform the logic of even a simple if, and with the assignment case, there is a minimum of 2 operations going on, first the assignment, then the equality.
if (flag = false) will set the flag variable to false, then check if(flag).
You are suggesting doing if(x = 1) which could set x to 1, but if(x) is not valid.
It would print 3 because the boolean variable is assigned false (and checked for true) then checked for false and finally for !false which is true.
The method is for a calculator and is supposed to return log2(n). All of the methods used (monus which is minus spelled wrong) power, ect) are written correctly. s(n) just adds one to n and p(n) subtracts one.
when I call the method in the main it gets the remainder right, but always returns 0 for the answer. this confuses me. I am sure it has to do with the fact that i am reinitializing answer to 0 each time the method is called but shouldn't that not matter because it is always going to get set to x before it returns anything?
x is a private static variable that has been set to 0 outside of the method.
public static long v(long n)
{
long answer =0;
if (power(2,x) > n)
{
x = p(x);
setRemainder(monus(n,power(2,x)));
answer = x;
}
else if(power(2,x) ==n)
{
setRemainder(0);
answer = x;
}
else
{
x = s(x);
v(n);
}
x=0;// reset x so it can be used again.
return answer;
}
can anyone help me?
You should change the line:
v(n);
to:
answer = v(n);
Right now, if the last else block is executed, the answer variable is not changed - so it's still 0.
As stated in the comments you make the recursive call in the else statement but don't assign this to anything when the recursive call returns.
Consider this:
On your first call: x = 0 so probably going to the else statement and enter the recursion. At some point of recursion one of your conditional statements will be true and in this case answer is returned but not assigned in the way back down the stack of recursive calls.
So would look like this:
1: v(n) // this calls v(n) again
2: v(n) returns answer = x // this returns an answer
1: returns answer = 0 // now the return falls down a level to where the recursive
// call was and the answer is lost as was not assigned
I would like to ask you guys a question. You see, I know what a for-loop is for but can someone please maybe explain how one works, just to help me get my head around it, an example is:
for(int i = 0; i < 10; i++) {
System.out.println("hello");
}
Now obviously that will just print Hello 10 times into the console but that's besides the point, I want to know how the for-loop works.
Sorry if i have confused anyone asking this - Shaun
The for loop in your example is more or less equivalent to this:
int i = 0;
while (i < 10) {
System.out.println("hello");
i++;
}
The only difference is that with your for loop, the variable i exists only within the scope of the loop.
Every for loop can be transformed into a while loop using this same pattern.
for (init; test; continuation) {
// loop body
}
becomes:
init;
while (test) {
// loop body
continuation;
}
Again, the only difference will be with the scope of any variables declared in init.
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Well, this is how it is set up:
for (a; b; c)
"A" is something that is done at the beginning of the loop. It can actually be left out if necessary, like this:
for (; b; c)
"B" must be a true or false statement (like i<10, it either is or it isn't). Once "b" is no longer true, the loop stops.
"C" is something that is done at the end of the loop.