Hi I have a following if condition in java
if ((i%3)==0)
do some work
else if ((i%3 || i%5)==0)----syntax error appears on this line
do some work
And it is showing me following syntax error...
Multiple markers at this line
- The operator || is undefined for the argument
type(s) int, int
- Syntax error on token "OR", . expected
- i cannot be resolved or is not a field
can any one please tell me how can i fix this one ??
You can't specify multiple conditions like that. The || operator operates on boolean values only; it can't operate on numbers the way you would like them to operate. You must specify each condition individually:
else if ((i%3 == 0) || (i%5 == 0))
In English, we would say "i is a multiple of 3 or 5" and we would know what you mean. It doesn't work that way in Java. You must be more explicit. The required Java code is equivalent to "i is a multiple of 3 or i is a multiple of 5".
You have to have the comparison with every part of the condition. In this case your else if should look like this
else if (i%3 == 0 || i%5 == 0)
the || operator can only be used on bool types. i%3 is an integer.
Logical operator can only applied to boolean conditions. you are applying OR condition for two integers. If your i is 10, then i%3 = 1 and i%5 = 0. So then you are evaluating (1 || 0). If you really want to do that then you should use bitwise operator (|). Otherwise, use parenthesis which you already used in the first if part. so it will be either
else if((i%3 == 0) || (i%5 == 0))
or
else if((i%3 | i%5) == 0)
Thanks
Related
I'm trying to update softcount for my Blackjack game to account for Aces being played (value 11 or 1). When using the short-form IF statement, why is the first line of code incorrect, but the second line is okay to use? Is this type of if statement limited?
(counter > 1) ? (softcount+=1) : (softcount+=value); // bad
softcount += (counter > 1) ? 1 : value; // good
It is simply how the language is defined.
Only certain expressions - statement expressions - can be made into a statement by adding ;. (Statement expression + ; is an expression statement).
From JLS Sec 14.8:
ExpressionStatement:
StatementExpression ;
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
Conditional expressions are not statement expressions.
The ternary has to be seen as a way to evaluate something and not as a way to apply a processing.
So it expects some expressions after ? but you wrote statements : softcount+=1 and (softcount+=value) in the first code.
In the second code, it is ok because you specified two expressions : 1 and value.
Besides do you really find this code a short hand ?
(counter > 1) ? (softcount+=1) : (softcount+=value); // bad
You repeat the increment part.
What you want in your case is just :
if (counter > 1) { softcount+=1;} else {softcount+=value;)
It is called ternary operator, it is used when you simply want to return a value based on condition. It's main purpose is to avoid if else for simple avaluations. In your case you should use if else.
Sorry that I am a noob...
I have a method which takes two specific command line arguments to create an object:
Number data = new Number(arg[0], arg[1]);
The acceptable arguments are:
arg[0] can only be: 10, 20 or 30.
arg[1] can only be: 2, 4 or 6.
How do I create a try and catch exception which ensures that two arguments have been provided and that the arguments are acceptable?
Thank you for your time in advance.
You definitely do not control the flow using try-catch - it's bad practice. For this reason, there is if-else statement.
boolean conditionArg0 = arg[0] == 10 || arg[0] == 20 || arg[0] == 30;
boolean conditionArg1 = arg[1] == 2 || arg[1] == 4 || arg[1] == 6;
if (conditionArg0 && conditionArg1) {
// input is fine, go on
} else {
// display error
}
You should check first if the array arg has at least 2 values, otherwise, the NullPointerException will be thrown.
In case of more allowed values is better to use Set<Integer> and search if the value is present. If the allowed values follow a pattern (ex. divisible by 10), then it's better to use the calculation instead of the Set.
Edit: Why is controlling the flow using try-catch considered a bad practice? It has been discussed many times here and here. There are a lot of arguments and I find the most important that (took from here):
Exceptions are for exceptional situations, not for normal flow control. One should use exception handling for handling unanticipated/exceptional situations, not as normal program flow, because otherwise, an uncaught exception will tell you much less.
Semantically, the use of if-else is a clean way to control the flow. You should always start with if-else and refactor in case the number of compared elements increase significantly.
Based on the comments,
First check if the length of the inputs is exactly 2.
Check for equality.
Code:
if(arg!=null && arg.length==2){
if( (arg[0].equals("10") || arg[0].equals("20") || arg[0].equals("30"))
&& (arg[1].equals("2") || arg[1].equals("4") || arg[1].equals("6")) ) {
Number data = new Number(arg[0], arg[1]);
}
else{
//Handle wrong input(s)
}
}
else{
//Handle wrong input(s)
}
By creating your custom exception class but it is not good idea. using if else is easy and good
In my enterprise application I have business rules like :
((AMOUNT < 20000.00) || ((AMOUNT >= 20000.00) && (RISKEXPOSURE == 'N')))
(ind = A1 || ind = A2 || ind = A3 || ind = S1 || ind = S2 || ind = S9)
The rule, as you can see, is made of business expressions ex: (AMOUNT < 20000.00).
The rules could have any number of business conditions joined by boolean operators && and ||.
The identifiers AMOUNT, RISKEXPOSURE and ind are the business variables (which could vary from 1 to n based on the business domain).
My requirement is to find those expressions when true make the entire rule true.
For ex:
for business rule #1 - the whole rule will be true if:
(AMOUNT < 20000.00) is true or ((AMOUNT >= 20000.00) && (RISKEXPOSURE == 'N')) is true hence my output should be:
Solution #1: (AMOUNT < 20000.00)
Solution #2: ((AMOUNT >= 20000.00) && (RISKEXPOSURE == 'N'))
Similarly for Business rule #2:
Solution #1:ind = A1
Solution #2:ind = A2
Solution #3:ind = A3
Solution #4:ind = S1
Solution #5:ind = S2
Solution #6:ind = S9
What I tried:
Since each business expression can be either true or false, I changed my business rule #1 as (A || ( B && C ) ). I used the propositional logic library from Tweetyproject. This gives me results but I cannot enforce a constraint such as an XOR. In my example A and B are mutually exclusive but my output possible results. Representing the rule in truth table form, I get all the following true conditions
011
,100
,101
,110
,111
However my result should be only 100, 011
This lead me to look for alternatives and the answer here suggested a constraint solver.
I have been reading about the Choco Solver. But I am not sure how my business rule can be represented in a model acceptable by the solver. Any help is greatly appreciated.
Simple solution can be to implement algorithm which find all combinations of boolean values of a given size. Then for each expression calculate the entire expression by the values in combination and the opposite value of your expression. If in every combination the whole expression calculation with the values in the combination row and with the opposite value for your expressions are different, the this expression is this which you need. I will try to explain it easily.
You have expression (A || ( B && C ) )= BIG
Then you find combinations of possible values: e.g
[[001],[010],[011]...[111]]
For each of them replace the values in to your BIG expression and compare the result the expression calculated by the opposite value of expression you want - [101] with [001] | [110] with [010] and for each combinations the result is difference you find the expression. Then switch to next index and do this again
I would recommend you to look at SMT solving. It naturally allows solving the stated problem. You introduce any reasonable amount of constraints (both integer and Boolean) and variables. Basically, it tries to satisfy an equation given some constraints. It will find first satisfying assignment to your task.
Links to explore:
Z3
CVC4
yices2
Be aware that runtime and performance are heavily dependant on the problem itself: constraints, constants, exact values.
I would be grateful if someone could please explain why the following is occuring. Thanks a lot.
boolean b = true;
// Compiles OK.
// The LHS "assignment operand" requires no ()parentheses.
if (b=true || b==true);
// Reverse the ||'s operands, and now the code doesn't compile.
if (b==true || b=true);
// Add () around the RHS "assignment operand", and the code now compiles OK.
if (b==true || (b=true));
Edit -
BTW, the compilation error for code line #2 is: "unexpected type", and occurs where the short-circuit OR operator is located:
if (b==true || b=true);
// ^ "unexpected type" compilation error occurs here.
Edit 2 -
Please note that the code fragments found in this question are examples of "highly artificial Java coding", and consequently would not be seen in professionally written code.
Edit 3 -
I'm new to this incredibly useful website, and I've just learnt how to make and upload screenshots of Java's compilation messages. The following image replicates the information that I provided in my first "Edit" above. It shows the compilation error for example code line #2.
The assignment operator = has lower precedence than the logical or operator || so that you can use the logical operator in an assignment without extra pairs of parentheses. That is, you would want to be able to write
a = b || c;
instead of being forced to write a = (b || c).
Unfortunately, if we work with operator precedence only, this rule also applies to the left hand side of the expression. a || b = c must be parsed as
(a || b) = c;
even if what you intended was a || (b = c).
Assignments have the lowest precedence in Java. Thus, your first two expressions are equivalent to:
if ( b = (true || b==true) );
if ( (b==true || b) = true );
The second one doesn't compile because the expression (b==true || b) is not an lValue (something that can be assigned to).
If you add parentheses, you do the assignment before the OR, and everything works.
Using operator precedence (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) we have this (I added parentheses to indicate precedence):
if (b=(true || (b==true))), b will be assigned to expression and returns boolean, so it fits for condition;
if (((b==true) || b)=true), left side doesn't fit for assignment operator (as it is expression rather than variable);
if (((b==true) || (b=true))), boolean comprates to boolean with OR, right boolean is boolean because b is variable and = returns the assigned value.
I'm trying to return a different value using a simple if/else to check for an even number in Java.
if (move % 2 == 0) {
return "o";
} else {
return "O";
}
I know in JavaScript you can use
if () : a ? b ;
Can this be used in Java?
Yes, you can use the ternary operator in Java:
return (move % 2 == 0) ? "o" : "O";
Just don't expect it to be any faster than the if-else.
Yes, you can use the conditional operator in Java:
return (move % 2 == 0) ? "o": "O";
It won't make your program any faster, but it's a little more concise and if you are familiar with the conditional operator, you will probably find it easier to read.
But conversely, if you don't know this operator it will be hard to guess what the code does.
Yes you can. It's called a ternary operator
Usage:
true ? case1 : case2; // returns case1
false ? case1 : case2; // returns case2
Instead of "optimizing" the if versus the ternary operator ? you should focus on the move % 2 == 0. If move is an integer and not a floating point variable this may be faster:
if( move & 1 == 0 )
return "E";
else
return "O";
Bit operations are usually faster than division or modulo calculations.
(conditional) ? if-true-statement : if-false-statement;
Yes it can, check out the Wikipedia page for Ternary Operators
There's no way you can use an if-statement in a more or less efficient way.
... and further more - keep in mind that, and this does not only apply for if-statements:
You should never try to optimize expressions used, for performance reasons - write code that focuses on readability (and in term, maintainability). The reason for this is that there's a JIT (Just-in-time compiler) that will optimize the bytecode, and modify the instructions you've specified in your byte-code.
If you're thinking about using the ternary operator, then consider, will this lead to harder to understand code (if you're multiple people working on the code). If it's just you working on the code then do as you please - and yes:
Object var = boolean-expression ? some-value : another-value;
is much more compact than:
Object var;
if (boolean-expression)
var = some-value;
else
var = another-value;
If you really need this to be blindingly fast, which is pretty dubious, you should also consider a lookup table:
static final char[] moveChar = {"o", "O"};
// ...
return moveChar[move % 2];
But I wouldn't implement any of the suggestions given here without timing them, and I wouldn't do anything at all until it had been proven that what you have now is really a bottleneck, by which I mean that it consumes more than about 50% of the CPU time.