(Code Review) Java if statement involving logical and(&&) operator [closed] - java

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have started programming a few weeks ago in java/android. I want to write a small tic tac toe game as an android app but I'm having trouble with my method that will check for the winner. It is as follows:
public void checkForWinner() {
if( taken[0] && taken[3] && taken[6] ||
taken[0] && taken[1] && taken[2] ||
taken[2] && taken[5] && taken[8] ||
taken[6] && taken[7] && taken[8] ||
taken[0] && taken[4] && taken[8] ||
taken[2] && taken[4] && taken[6] ||
taken[1] && taken[4] && taken[7] ||
taken[3] && taken[4] && taken[5] == 1 ){}
}
Here I have an array called taken that holds 9 integers, each of those integers being either a one, meaning player one owns that block, or a two, meaning player two ows that block. Current, I am trying trying all possible scenarios in which player one would be the winner but eclipse is telling me that The operator && is undefined for the argument type(s) int, int. The error only seems to be showing for the first logical and operation of each line of the if statement. For example the first error goes up to taken[0] && taken[3] and then disappears until the next line.

Alternatively, you can check taken[n] values to see if they hold 1 or 2, if you think that'd make your code clearer:
(taken[0]==1 && taken[3]==1 && taken[6]==1)
Keep in mind that the && operator expects boolean operands...so it won't work with your int array the way you're expecting it to.

Swap your && to ==, you're trying to see if they're all the same value I assume which would show a winner, and be sure to use parentheses to sort it out, so one win condition would look like
((taken[0] == taken[3]) && (taken[0] == taken[6]))
However, this will only tell you that some player won, not which player. I guess you could check to see which player made the last move once it is determined that some one has won and declare that player as the winner.

In java,
if (a && b) or if (a || b)
works only if a and b are booleans / boolean expressions.

Here I have an array called taken that holds 9 integers, each of those integers being either a one, meaning player one owns that block, or a two, meaning player two owns that block.
In that case, you can replace the logical operators with bitwise operators:
int winner = taken[0] & taken[3] & taken[6]
| taken[0] & taken[1] & taken[2]
| taken[2] & taken[5] & taken[8]
| taken[6] & taken[7] & taken[8]
| taken[0] & taken[4] & taken[8]
| taken[2] & taken[4] & taken[6]
| taken[1] & taken[4] & taken[7]
| taken[3] & taken[4] & taken[5];
Then the variable winner will contain 1 if player 1 won, 2 if player 2 won, 0 if neither of them won, or 3 of both of them won (which probably isn't possible in your game).

1) You cant use && or || operators on int variables because the are meant for boolean values.
2) also use brackets to group conditions like
if (
(taken[0]==1 && taken[3]==1 && taken[6]==1)||
(taken[0]==1 && taken[1]==1 && taken[2]==1)||
...

OK there are two main problems here.
First, taken[0] needs to return either true or false to be able to remain as-is within the if-statement. You have mentioned it is an integer, so for it to return true or false, you'll need to do a comparison, such as taken[0] == 1.
Second, you need to use parentheses and do some groupings. Java does not respect whitespace. Instead of if( taken[0] && taken[3] && taken[6] || ..., you'll need to do if( (taken[0] && taken[3] && taken[6]) || .... That is, you need to put parentheses around each set of groupings.
The reason Eclipse is erroring is because the && operator is only for comparing booleans. That is true && true. You're giving it integers and it doesn't like that.
One way you might want to solve this is to write a function that determines if a solution is reached. So maybe something like:
private boolean isSolutionPresent(int[] taken, int index1, int index2, int index3) {
return (taken[index1] == 1 ) && (taken[index2] == 1) && (taken[index3] == 1);
}
Then you could convert your if statement to something like:
if (isSolutionPresent(taken, 0, 3, 6) ||
isSolutionPresent(taken, 0, 1, 2) ||
isSolutionPresent(taken, 2, 5, 8) || //... etc, removing the final ==1
Since the isSolutionPresent method returns a boolean (that is, true/false) you can apply the || operator to it.

Related

Is there a limit to how long an if statement can be in Java?

I was working on a game called the L game. In the function to check for a win, I had an if statement like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0") && buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0") && buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0") && buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0") && !(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(colour))) {
return false;
}
And this code didn't work. Not that I was getting an error, just it was not doing what it was supposed to do when a player won. However changed it to a few if statements in each other like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0")) {
if (buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0")) {
if (buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0")) {
if (buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0")) {
if (!(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(
return false;
}
}
}
}
}
And this does work.
Your two code snippets behave differently not because you have exceeded some "maximum characters in an if statement" limit, but because && has a higher precedence than ||.
When you say:
A || B && C || D
You meant
(A || B) && (C || D)
But without any parentheses, Java thought you meant:
A || (B && C) || D
This is because && has a higher precedence than ||. It's kind of like how you do multiplication first, than addition.
That aside, there is theoretically no limit on how long an if condition can be. It is not specified in the Java Language Specification. As long as you have enough RAM for the compiler, disk space to store the source file, and time for the compilation process, your code should compile eventually, if we assume the compiler implements the spec perfectly.
This doesn't mean that you should be writing super long if statements, though. Code is not only read by computers. Arguably, it is more often read by people than computers. So please keep that in mind when writing code.
A first step to refactoring your code would be to write a method like this:
private bool isButton0(int x, int y) {
return buttons[x][y].getText().equals("0");
}
so that you don't have to repeatedly say buttons[i][1].getText().equals("0").

If else condition combine && and || in one row statement

Thank you for your time, i create some if else statement in checkbox to display result, can i combine && and || condition in one statement? for example
if (radioMale && chestPain && (leftArm || bothArm || jaw || throat)) {
highPossibilityOfHeartDisease = true;
}
User have to tick radioMale && chest pain && can tick either leftArm, bothArm, jaw or throat (one or more) to return true for highPossibilityOfHeartDisease. Is the code above valid? need some help here.
Yes you can combine && and || in a if...else statement. See it logically before considering programmatic side.
true AND true AND true AND (true OR false OR false) the condition inside brackets will be verified and set as one resulted Boolean that may be true or false according to the condition.
Then the resulting booleans will be verified linearly as normal.
You can read some articles explaining maths of boolean expressions, for example:
The Mathematics of Boolean Algebra: From StanFord University
Boolean Expressions
Boolean algebra

while loop conditions java

String userGuessParameters = "a,b";
while (!Character.isDigit(userGuessParameters.charAt(0)) ||
!Character.isDigit(userGuessParameters.charAt(2)) ||
userGuessParameters.length() != 3 ||
(int)(userGuessParameters.charAt(0)) >= parameters[0] ||
(int)(userGuessParameters.charAt(2)) >= parameters[1]) {
System.out.print("Mida kaevame (rida, veerg): ");
userGuessParameters = userInput.nextLine();
userGuessParameters = userGuessParameters.replaceAll(" ", "");
}
I'm trying to check if all the required conditions are fulfilled in the while loop. parameters is what user entered in array form. Let's assume parameters = [4, 4] (Parameters is used to create a 4x4 map).
I need userGuessParameters to be:
Numbers
Length equal to 3 (the input looks like this: 2,2 when the spaces are removed)
Smaller than the biggest coordinate (which is 3,3)
But for some reason, the loop never exits. I'm almost certain it is because of the last two conditions in the while loop, but I can't find the mistake.
You are using the logical OR operator when you should be using AND (you want all the conditions to be met, not just at least one of them).
Use the java notation for AND which is &&:
(!Character.isDigit(userGuessParameters.charAt(0)) &&
!Character.isDigit(userGuessParameters.charAt(2)) &&
userGuessParameters.length() != 3 &&
(int)(userGuessParameters.charAt(0)) >= parameters[0] &&
(int)(userGuessParameters.charAt(2)) >= parameters[1])
Try to use && instead of || like this:
while (!Character.isDigit(userGuessParameters.charAt(0)) && !Character.isDigit(userGuessParameters.charAt(2))
&& userGuessParameters.length() != 3 && (int)(userGuessParameters.charAt(0)) >= parameters[0]
&& (int)(userGuessParameters.charAt(2)) >= parameters[1]) {

While loop seems to ignore "or" operator

I'm having trouble figuring out what's wrong with my code for a "rock paper scissors" game for my Comp Sci class. The part I'm having trouble with is this:
while((userscore < 4) || (compscore < 4)){
if(userhand.equalsIgnoreCase("R") && comphandint == 0){
JOptionPane.showMessageDialog(null, "Rock vs. Rock: \nYou Tie");
}
else if(userhand.equalsIgnoreCase("R") && comphandint == 1){
compscore += 1;
JOptionPane.showMessageDialog(null, "Rock vs. Paper: \nYou Loose");
...
}
The loop works except for the fact that it loops until both userscore and compscore are equal to 4. I want it to loop until only one of the two hits 4. Any ideas?
You should use && (and) rather than || (or).
A simple logic table shows us the result of both;
| AND | OR
value1 | true | true
value2 | false | false
result | false | true
(This is for the benefit of others finding this question later)
So as you can see, with OR if either of the values are below 4 then true will be returned and the loop will be entered. With AND, as long as one of the values is 4 or above false will be returned and the loop will stop - as you wanted.
Hope this helps you, and anyone else who finds this question in future.

Is there any way to force java to test two condition regardless the first condition? [duplicate]

This question already has answers here:
Is there a way to disable short circuit evaluation in Java?
(3 answers)
Closed 8 years ago.
let's say I have a statement
if(stack.pop() == 1 && stack.pop() == 1)
if top of stack is 0, then the second condition won't be implemented, which means it just pops one value at the top. What I want is to pop both, the top and the value after top. Is there any way to do that without using another if-else statement in it?
int first = stack.pop();
int second = stack.pop();
if (first == 1 && second == 1)
Use the bitwise AND operator**:
if( stack.pop() == 1 & stack.pop() == 1 )
This will force the evaluation of both sides.
** I know it by "non-short-circuiting" of logical AND, but it is indeed a bitwise operator that acts on boolean operands (documentation here).
Update: As JBNizet said in his comment below, this code is "fragile", since some developer may "correct" the operator to the short-circuit version. If you choose to use & instead of storing the values of the method calls (forcing them to run) likewise JBNizet answer, you should write a comment before your if statement.
Yet another one-line and slightly obfuscated way to do this:
if( stack.pop() == 1 ? stack.pop() == 1 : stack.pop() == 1 && false )
Personally I'd go for JB Nizet's way. Makes it as clear as can be exactly what you're trying to do.
easiest, I found is (if stack only contains 0 and 1):
if(stack.pop() + stack.pop() == 2)
or JB's solution with one variable:
int first = stack.pop();
if (stack.pop() == 1 && first == 1)
Here is an approach that will bypass the EmptyStackException thrown when the stack has fewer than two elements.
if (stack.size() > 0) {
int first = stack.pop();
if (stack.size() > 0) {
if (first == 1 && stack.pop() == 1) ; //do something here
}
}

Categories

Resources