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.
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.
I was implementing an N-nary tree (here N=4) and want to put in a logic to do something if the boolean property val of all four children of a node are equal, I tried with:
if (childOne.val == childTwo.val == childThree.val == childFour.val){
doSomthing();
}
however this doesn't work for my test cases, so I have to change it to a more explicit and verbose:
if (childOne.val == childTwo.val && childTwo.val == childThree.val && childThree.val == childFour.val){
doSomthing();
}
and this one works. However I cannot make sense why the first evaluation doesn't give me the correct answer.
The == operator is left associative, so your first expression looks like this with brackets added:
(((childOne.val == childTwo.val) == childThree.val) == childFour.val)
Here's a case where the above will be true, but not all four values are the same:
child 1 and 2 are false
child 3 and 4 are true
Another way of doing this:
Stream.of(childOne.val, childTwo.val, childThree.val, childFour.val)
.distinct().count() == 1
I suggest you stick with the plain old && because there isn't a BooleanStream and the booleans need to be boxed.
Another class is going to pass in random numbers into this method(x,y,z). I want to know the boolean that does returns true from my last if() statement, so I can do operations on it. I have explained my logic in the comments.
I am still really new to this, so my logic may be wrong.
public static String FindDate(int x, int y, int z) {
boolean istrue1 =(x >= 1 && x <= 31);
boolean istrue2 =(y >= 1 && y <= 31);
boolean istrue3 =(z >= 1 && z <= 31);
if(istrue1 ^ istrue2){
if(istrue1^istrue3){
if(istrue2^istrue3){//now knowing that no values are the same, i can find the true value.
if(istrue1||istrue2||istrue3){
// I want to store/use/print/know which bool(istrue) that evaluated to true, so I would know if it is
//x,y,z that went through the algorithm successfully.
}
} else{return "Ambiguous";}
}else{return "Ambiguous";}
}else{return "Ambiguous";}
return "true"; //I would actually end up returning the value that went through the algorithm
}
You can store boolean values just like any other type in Java. I'm not sure exactly what your last comment means by "the value that went through", but if you want to keep track of the result of a particular test, you don't necessarily need to write something like
if (a == b) {
return true;
} else {
return false;
}
In that case,
return a == b;
is equivalent. If the expression is more complicated parens are a good idea.
return ((a == b) || c);
And instead of returning, you could always store the result and do something with it later.
bool test = ((a == b) || c);
action(test);
You can your following: But your condition is incorrect 3 variable for two value (true, false) all can't be different. So your logic always return "Ambiguous"
if(istrue1 ^ istrue2){
if(istrue1^istrue3){
if(istrue2^istrue3){
//now knowing that no values are the same, i can find the true value.
if(istrue1||istrue2||istrue3){
// I want to store/use/print/know the bool that evaluated to true, so I would know if it is
//x,y,z that went through the algorithm successfully.
return "true";
}
}
return "Ambiguous";
Instead of:
if(istrue1||istrue2||istrue3)
Its is easiest to just break it down into 3 differnt if statement.
if(istrue1)
if(istrue2)
if(istrue3)
No easy trick that i was hoping for. sad day.
Also the statements i did with the xor(^) operators turns out to be bad logic.
it would be easiest to this:
if(a&&b || a&&c || b&&c)
That would return ambiguous if any combo are both true.
However thats not the original question, but I thought i might as well mention it.
I have a series of four yes/no choices in four separate dialog boxes, the cumulative results of which will lead to one of twelve separate links (e.g., Yes/Yes/Yes/No -> link A, Yes/No/No/Yes -> link B, etc). The branching logic uses boolean values.
Here's what I have so far...just the first dialog box and printing the results for validation.
public class OutageGuideSelector{
public static void main(String[] args){
boolean contactServerUp;
boolean vistaUp;
boolean stormOutage;
boolean vistaCSUp;
//
int contactServerEntry = JOptionPane.showConfirmDialog(null,
"Is the contact server up", "Please select",
JOptionPane.YES_NO_OPTION);
System.out.println("result from entry " + contactServerEntry);
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
/* System.out.println(contactServerUp); */
}}
Right now, the results of clicking YES reults in a 0 being returned, NO results in a 1. Is this normal, seems counterintuitive, and there's nothing at docs.oracle.java that shows a clear example of the output values except this which seems to suggest that the public static final int YES_NO_OPTION default in 0.
Additionally, the line System.out.println(contactServerUp); comes back with an error that the field contactServerUp might not have been initialized when I un-comment it, so I can't see if my convert-int-to-boolean is working.
First: It appears that JOptionPane method does not include any boolean returns...except getWantsInput() which returns the value of the wantsInput property...so I assume I'm already being the most efficient I can with this. I'd like to know if there's an easier way.
Second, what am I missing that prevents my console output statement from recognizing the contactServerUp? Where's my misplaced semicolon?
According to the javadoc, when one of the showXxxDialog methods returns an integer, the possible values are:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
You should test against those constants:
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
The value returned by the the JOptionPane dialogs are values defined as constant fields in the class.
Although, indeed, one could assume that 0 means false and 1 means true, the values are more ids for the different buttons a dialog can have.
To know if the user pressed yes or no, you can compare the return value to the constant fields described here. For example, in your case :
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
Since a dialog a JOptionPane can have more than two possible 'answers' a boolean would be a poor representation. You are forgetting about the YES, NO and CANCEL option, or what about just a OK answer.
If it would have been written today, I suspect a Enum would have been used instead of an int.
As for the second question, the compiler does not allow access to uninitialized variables.
When you do the following, there is a chance that the variable might not be initialized:
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
What if, for example, contactServerEntry == JOptionPane.CLOSED_OPTION? In that case, your boolean value is never initialized.
You need to add an else clause at the end of your if-else chain, or initialize contactServerUp value to a default value in the beginning.
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.