Checking boolean values in 2d array - java

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.

Related

How to compare two datasets to check for missing rows which don't exist in the other dataset?

I have built a method which takes two datasets: dataset1 and retirementSimpleData.
It matches the two datasets based on a primary key/number, defined as cnum, in the code below.
I wanted to return the value of the difference between the getAssets value and the getSums value, and this is working, except for one little problem.
Some of the cnums that exist in dataset1 don't exist in retirementSimpleData. Similarly, some cnums which may exist in retirementSimpleData may not exist in
dataset1. This is resulting in no data being returned for that cnum.
I would like to implement two passes at the end which check in one direction to see if I missed anything. The second pass would check in the opposite direction.
However, not sure how I would go about implementing this.
public void getReportData(int index) {
String date1 = Util.dateTimeToShortString(reportDate);
String date2 = reportDao.getPreviousRetirementDate(date1);
List<SurveyCompareAssetsCheckData> dataset1 = reportDao.getSurveyCheckCompareAssetsData(date1);
List<RetSurveyAssets> retirementSimpleData = reportDao.findRetSurveyByDate(date1);
for (SurveyCompareAssetsCheckData surveyCompareAssetsCheckData : dataset1) {
for (RetSurveyAssets surveyCompareAssetsCheckData2 : retirementSimpleData) {
if (surveyCompareAssetsCheckData.getCnum() == surveyCompareAssetsCheckData2.getCnum()) {
surveyCompareAssetsCheckData.setRetirementsimple(surveyCompareAssetsCheckData2.getSums());
surveyCompareAssetsCheckData.setDifference(surveyCompareAssetsCheckData.getAssets() - surveyCompareAssetsCheckData2.getSums());
Caveat: dataset1 and retirementSimpledata both use existing SQL pulls which I am not allowed to touch, otherwise I would have simply defined new SQL for these methods in my "DAOImpl." Therefore, I have to work with the data I am getting, and programmatically check for this.
Below, is the report which is being generated with my code. As you can see, I am ending up with zeros, which is showing the difference (incorrectly) as zeros, because Cnum #45, in this example simply doesn't exist in the second dataset (retirementSimpleData)
What is the datatype of Cnum, if it is int then default value is Zero.
You have to add else-if condition to check for example:
else if (surveyCompareAssetsCheckData2.getCnum()== 0){
-------- logic here --------------------
}
else if (surveyCompareAssetsCheckData.getCnum() ==0){
----------logic here -----------
}

How to check multiple statements?

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.

Using Boolean True/False with JOptionPane.YES_NO_OPTION

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.

Java searching an array for repeating pattern

I have a program that is searching a maze to find the best way out. As it searches it adds the next move to an array. My problem is that it keeps repeating the same three moves over and over. I need to find the best way to check that array of moves in order to force it to change move when a loop has been detected.
edit for clarity,
http://www.logicmazes.com/theseus.html maze three is the one I'm testing. what happens is that it gets stuck moving up and down in the column it starts in.
You could keep track of every cell your current path has already visited, and not go to those cells again (since that would create a loop).
As far as the data structure is concerned, I see two main possibilities:
keep an array -- or a set -- of coordinates that you've visited; or
have a boolean array of the same dimensions as the maze, setting the visited cells to true.
You would need to update the structure whenever you take a step, and whenever you backtrack.
It sounds like the problem is that your "state" doesn't actually contain enough state information. In every cycle, after Theseus has moved and the Minotaur has moved twice, the state consists of the following:
Theseus's x-coordinate.
Theseus's y-coordinate.
The Minotaur's x-coordinate.
The Minotaur's y-coordinate.
You can represent these as some sort of MazeState object whose equals and hashCode methods make it easy to see if two instances represent the same state.
Since the Minotaur's motion follows a very rigid program, every move that Theseus makes (left/right/up/down/delay) will move from one well-defined state to another. You then need to forbid Theseus from making any moves that:
Would cause the Minotaur's x- and y-coordinates to equal those of Theseus (since this means Theseus is dead).
Would cause the new state to be equal to a state that you've previously been in (since this means that no progress has been made).
To do this, you can store the previous states in a HashSet<MazeState>.
If you are using an Array then you should be able to use "contains" method to check if the move is already in the array.
In order to do that you may have to modify your equals method to compare two different moves to check if they are the same.
In that case, when you identify the same move, you can ignore that and look for other moves. An example pseudo code
public class Move {
int x;
int y;
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Move) return false;
Move other = (Move) o;
if(this.x != other.x) return false;
if(this.y != other.y) return false;
return true;
}
}
public class SolveMaze {
List<Move> moves;
...
public boolean isValidMove(Move move) {
if (moves.contains(move)) return false;
else {
...
moves.add(move);
}
}
}

Java Beginner Boolean Question

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.

Categories