Java and and or operator not working - java

I am using the following statement to break out of the loop when two conditions met:
while (true)
{
if (uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4)
&&
uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)){
break;
}
The loops breaks when one or both && conditions are met. However, I wrote the code to break the loop ONLY when both conditions are true.
Is there something missing from above statement?
Regards,
Shei7141.

wrap them in parentheses
if ( (uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4))
&&
(uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)) )
or
even make a HashSet of correct answers and do this will be clean and will be efficient too
answers1Set.contains(uAnswer1) && answers2Set.contains(uAnswer2)

above code shows that uAnswer1.equals(answerB4) && uAnswer2.equals(answerS1) are in AND condition
while (true)
{
if ((uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4))
&&
(uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2))){
break;
}

while (true)
{
if ((uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4))
&&
(uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)))
break;
}

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").

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]) {

java: if.else strange behaviour

i've a problem with a couple of if-else conditions, here's the code:
if((hour<=16 && min<30)||(hour>=21 && min>0))
{ //copy of if#3
Log.d("baja", "copy");
message="something2";
}
if ((day>=1 && month>=4) && (day<=30 && month<=9))
{ //if#1
if((hour<=16 && min<30)||(hour>=23 && min>0))
{ //if#2
message="something";
}
}//end of if#1
else
{ //else for if#1
Log.d("baja", "before if#3 ");
if((hour<=16 && min<30)||(hour>=21 && min>0)){ //if#3
Log.d("baja", "if#3");
message="something2";
}
}
the problem is that if the flow enters the else if#3 doesn't work, but the copy i've put outside if#1 works perfectly....what is the problem?
i can't post the exact log now, but i can see "copy" and "before if#3"
I think I know what you are trying to do (If I understand your question correctly). The reason for this is that the else block is attached to the high level if block, rather than it's internal logic. If the if#1 returns false, nothing will happen, if it is true it will test if#2 -> if this is false, it will execute the else statement. If this is not your question, please supply the stack trace as rattmuff requested
if ((day>=1 && month>=4) && (day<=30 && month<=9))
{
if((hour<=16 && min<30)||(hour>=23 && min>0))
{
message="something";
}//if#2
else
{
Log.d("baja", "before if#3 ");
}//else
}//if#1
else if((hour<=16 && min<30)||(hour>=21 && min>0))
{
Log.d("baja", "if#3");
message="something2";
}//if#3

Dynamic Conditional Statement

I want to create dynamic conditional statement in java
following are my expression in file,There are hundreds of expression and they keep on changing
0001|((condition1 == 100) && ((condition2 == 1) || (condition2 == 2) || (condition2 == 3)) && (condition3 > 74))
0002|((condition1 == 100) && ((condition2 == 1) || (condition2 == 2) || (condition2 == 3)) && (condition3 > 59) && ((condition4 == 3) || (condition5 > 30)))
These expression are hardcoded in my class.
if(condition1==100 && ((condition2 == 1) || (condition2 == 2) || (condition2 == 3))){
if(condition3>74){
return "0001"
}
if(condition3>59 && ((condition4 == 3) || (condition5 > 30))){
return "0002"
}
}
i want to create dynamic conditional statement like
first i have check for all expressions which have condition1==100
then for ((condition2 == 1) || (condition2 == 2) || (condition2 == 3))
then return value according to final condition
it is something like first DFS and then BFS
can some body can give me idea how to check first Depth and then Bredth First in java
Your case is : You want define very many conditions and change it continous. You need to have a solution for change dynamically expression and define new condition.
There are two solution for dynamic situation such as your case:
Using Rule Engine. This has very benefit, you can see more information from http://java.sun.com/developer/technicalArticles/J2SE/JavaRule.html
and you can see its open source implementation from here .
Using Dynamic Language or Script Language and Script api.
in second solution you have several choise. I writing some in following:
Groovy: A complete and wonderful script language. see http://groovy.codehaus.org/
Spring Expression Language: Spring solution for calling simple expression. see http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html
BeanShell: A simple but wonderful script language.
There are more dynamic language such as JRuby that you can see it by simple searching in web.
You can read more information for Script api in java from here.
Edited:
For sample, you can use BeanShell Script Language as follwoing:
First create a file with name test.bsh containg blow contents:
if(variable_1 == 100 )
{
System.out.println("Sample condition checked and is true.");
}
else
{
System.out.println("Sample condition checked and is false.");
}
Second set variable_1 from java:
import bsh.*;
Interpreter bsh = new Interpreter ();
bsh.set ("variable_1", 100);
and in final call script as following:
bsh.source (script);
and result will be as following:
Sample condition checked and is true.
by this approach you can change test.bsh content without recompile or restart.

Unknown while loop usage

This page a user must choose between one of 2 checkboxes 5 times. So I wrote this:
if (box1a.isSelected() == true || box1b.isSelected() == true) {
if (box2a.isSelected() == true || box2b.isSelected() == true) {
if (box3a.isSelected() == true || box3b.isSelected() == true) {
if (box4a.isSelected() == true || box4b.isSelected() == true) {
if (box5a.isSelected() == true || box5b.isSelected() == true) {
with some other things he does when it is true.
} else {
new Error("You must select an answer at all the questions");
}
Then he only returns a error if you don't check one of the top checkboxes. Then cleary I need a while loop in there but i don't know how to uhm do it. I know how a while loop works but don't know how It would look in this situation. Please help
Also now I have to do the same with text fields and using th same methode that I got answered by you guys doesn't work. any advise?
if ((box1a.isSelected() || box1b.isSelected()) &&
(box2a.isSelected() || box2b.isSelected()) &&
(box3a.isSelected() || box3b.isSelected()) &&
(box4a.isSelected() || box4b.isSelected()) &&
(box5a.isSelected() || box5b.isSelected()))
{
//true stuff
}
else
{
new Error("You must select an answer at all the questions");
}
You should never shouldn't test for true with ==. It is poor style, better to just use the return value from isSelected()
if ((box1a.isSelected() == true || box1b.isSelected() == true) &&
(box2a.isSelected() == true || box2b.isSelected() == true) &&
(box3a.isSelected() == true || box3b.isSelected() == true) &&
(box4a.isSelected() == true || box4b.isSelected() == true) &&
(box5a.isSelected() == true || box5b.isSelected() == true)) {
//DO SOMETHING IF TRUE
}
else {
new Error("You must select an answer at all the questions");
}
No looping needed ^_^
why don't you use radio button (with a default radio button checked) in this case ?
A general strategy would be something like this:
bool flag = true;
do{
//search for input
if (/*the input is valid*/)
flag = false;
}while (flag);
But if you hard code so many options, you might have the wrong design. Try something like a radio button like Jerome C. suggested.
if(!box1a.isSelected() && !box1b.isSelected()) {
// You must select an answer at all the questions
}
else if (box1a.isSelected() && box1b.isSelected() && box2a.isSelected() && box2b.isSelected() && box3a.isSelected() && box3b.isSelected() && box4a.isSelected() && box4b.isSelected() && box5a.isSelected() && box5b.isSelected()) {
// with some other things he does when it is true.
}
A few points to note here.
Avoid using class names like Error as they're normally used for genuine java.lang.Error logic.
If you have a boolean, you don't need to use a == operator.
Not sure why you want a while-loop. If you are thinking that the user must "stay in the loop" while the your condition (all 5 questions answered) is not met, then it is unnecessary. The Event Dispatch Thread (EDT) will continue running the "loop" for you.
On the other hand, if you are looking for a compact way to verify all of your checkboxes, you can change how they are declared from (assuming) javax.swing.JCheckbox box1a; etc. to either a fixed array or an ArrayList which you can then iterate over with a for-loop.

Categories

Resources