Multiple operators AND OR - Java - java

My code don't work. I expected to get the alert "You have xyz ....". Nothing happen. Its something wrong in the code?
if ((event.values[0] == 1 || event.values[0] == 2 || event.values[0] == 3)&&
(event.values[1] == 3 || event.values[1] == 4 || event.values[1] == 6)&&
(event.values[2] == 7 || event.values[2] == 8 || event.values[2] == 9)) {
values.setText("You have xyz ....");
}

Syntactic I don't see any obvious errors, however why you don't see your alert must be a result of incorrect values in your event[] variable. Have you tried debug your code?? To be sure what the values are?

Most probably the variables are wrong. I don't see a mistake in your code.

Related

Java and and or operator not working

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;
}

How to call a Java function in the 'when' part of the drools rule?

I have been searching for a while now, but I can't find the exact answer to my question anywhere, or if I find something similar, it doesn't works.
I want to call a simple java method in the when part of the rule.
My code looks like this:
rule "Ret Rule"
when
Map(this["LOYAL"] == "true")
Map(this["LOYALTYPROMORETENTION"] == "true")
PromotionValidityPeriod(promotionName == "VIVACLUB Loyalty Promo 2013 25 percent")
$customer: Customer( segment == "Residential" , $assets : assets )
$o: Order( ( (DPOrderType == 17 && retentionReason == "RET") || (DPOrderType == 2 && reason == "557") ) , $ct: contractTerms == 24, $olis: orderLineItems )
$tariff: OrderLI( part in ("DT2319", "DT2320"), actionCode not in ("Delete", "INVALID"), $parentId : parentId) from $olis
OrderLI( part == "DT2316", nodeId == $parentId, actionCode not in ("Delete", "INVALID"), $assetId : assetId ) from $olis
/*Asset( assetId == $assetId,
( (contractTerms != null && contractEndDate != null && eval(CalculationsHelper.getFullMonthDifference(new Date(), contractEndDate) < 3 ))
|| (contractTerms == null) ) ) from $assets*/
$li : OrderLI( $newTariff : part in ("DT2319", "DT2320"), parentId == $parentnodeid, actionCode == "Add") from $olis
$del : OrderLI( $oldTariff : part, parentId == $parentnodeid, actionCode == "Delete", productType == "Calling Plan") from $olis
eval(OrderDwrController.setTransitionCondition(fromTariff == $oldTariff, toTariff == $newTariff) == true
then
Offer of = new Offer("DT2331", $parentId, 7);
System.out.println($tariffOld);
of.getOrderLineItemAttributes().add(new OrderLIAttribute("DURATION", "" + $ct));
of.getOrderLineItemAttributes().add(new OrderLIAttribute("Discount of MRC", "25%"));
of.getOrderLineItemAttributes().add(new OrderLIAttribute("VIVACOM TV Package", $tariff.getProductNameENU()));
of.setProductNameENU("VIVACLUB Loyalty Promo 2013 25 percent");
$o.addOffer(of);
of.setLoyaltyPromo(true);
$o.addTextForOffer(of, new Integer[]{173});
end
The particular line where I have a problem is the very last one in the when part:
eval(OrderDwrController.setTransitionCondition(
fromTariff == $oldTariff, toTariff == $newTariff) == true
I just want to call a simple function
(OrderDwrController.setTransitionCondition(
fromTariff == $oldTariff, toTariff == $newTariff))
like the one above mine
(eval(CalculationsHelper.getFullMonthDifference(
new Date(), contractEndDate) < 3 ))
The function is static, returns a boolean value. I have imported the class in the beginning of the file.
What am I doing wrong?
1st of all you didnt close the eval().
2nd if you upgrade your drools you could just write java expressions in the then section and it'll be faster than eval()
Sorry for posting an answer instead of just replying to you (Don't have enough reputation yet :))
Whatever you put inside an eval must evaluate to a boolean. I am not sure yours is. That could be the problem.
Hope that helps
Cheers,
Avinash

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

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.

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