I'm extremely new to Java, and I'm currently using a Jar allowing the use of some 'Robots learning system'. However, there's one problem I've encountered.
while(robot.getX()!=1 && robot.getY()!=5) {
// blah
}
Here, I want the robot to prefer blah while both the X isn't 1, and the Y isn't 5 at the same time. When I use it in the provided format, however, it will only do as I instruct while neither his X is 1 or Y is 5, which isn't what I desire.
How can I pull this off? I've tried looking around on the internet, not sure how well I did not knowing the most technical keywords, and in the back of my mind I couldn't think of any double-indented if situation where it'd do as I wish. How can I do this?
Your condition becomes false as soon as either of its two parts becomes false. You need to invert the whole AND, like this:
while(!(robot.getX()==1 && robot.getY()==5))
...
or use an OR, like this:
while(robot.getX()!=1 || robot.getY()!=5)
...
(both loops use the same logical condition transformed using De Morgan's Law).
Use
while (!(X == 1 && Y == 5)) {
blah
}
Related
If x and y are int variables. Are the following two segments of Java code behaviourally equivalent for all values of x and y? Explain why, or why not.
Version 1:
if (x > 10)
{
if (y < 20)
{System.out.print("hi");
}
}
Version 2:
if (x > 10 && y < 20)
{
System.out.print("hi");
}
I think it is equivalent but I just want to make sure I'm not missing anything. I don't see how they cannot be equivalent. Thanks.
Yes, they are completely equivalent. In situations like these it comes down to picking the one you think is clearest.
Yes, they are.
The important point which might not be so obvious is that in both versions the second comparison is only evaluated if the first one results in 'true'.
Yes, they are equivalent, but the second one is shorter, and you can add a single else clause, which you cannot do in the first, because you'd have to write two independent else clauses there.
Whether one or two else clauses should be used depends on what your logic requires, so both forms may be appropriate.
I would generally recommend the second one, but if you don't need a single else clause, and the expressions are large, the first one may end up being more readable.
Yes they are equivalent also from the semantic point of view.
I'm writing small program, and want to get access to an element in array with the loop. And I need to increment "array index" variable for next iteration.
Here is the code:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].equalsIgnoreCase("O") ? false : winner[turn];
turn++;
Is it possible to make one line of code from it?
PS: I'm trying to write less lines only for myself. It's a training for brain and logic.
Well, it can be done for sure:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].
equalsIgnoreCase("O") ^ winner[turn++];
Look that there is not even ternary operator there.
But not because it is shorter it is better (and certainly not clearer). So I'd recommend you do it in these many lines:
String aSubField = subField[(int)Math.floor(i / 10.0)][i % 10];
if (aSubField.equalsIgnoreCase("O"))
winner[turn] = false;
turn++;
Look, even there is no need to assign the value in case the comparison yields false.
[edit]
YAY! Just found my XOR was wrong ... that's just the problem with golf, it tooks a lot of time to figure it is wrong .... (in this case, if the cond is true but the previous value is false, it won't work).
So let me golf it other way :)
winner[turn] = !subField[i/10][i%10].equalsIgnoreCase("O") & winner[turn++];
Note the ! and the &
[edit]
Thanks to #Javier for giving me an even more compact and confuse version :) this one:
winner[turn++] &= !subField[i/10][i%10].equalsIgnoreCase("O");
Let's break it down a bit. What you have is:
winner[turn] = (some condition) ? false : (expression involving turn)
(increment turn)
Well, why not increment turn in the array access? That means it'll be incremented by the time you evaluate expressions on the right hand side, but you can easily adjust it back to its previous value as needed.
winner[turn++] = (some condition) ? false : (expression involving (turn - 1) )
I'd like to know some cases in Java (or more generally:
in programming) when it is preferred in boolean expressions to use the unconditional AND (&) instead of the conditional version (&&).
I know how they work, but I cannot think about a case when use the single & is worth it.
I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional & instead of &&. (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)
(To give specific examples, x > 0 is going to be super cheap and side-effect-free. Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway? Sure, since it's a boolean the end result is going to be used in a branch anyway, but if (x >= 0 && x <= 10) involves two branches, and if (x >= 0 & x <= 10) involves only one.)
The only difference is that && and || stop the evaluation as soon as it is known. So for example:
if (a != null && a.get() != null)
works well with &&, but with & you could get a NullPointerException if a is null.
The only case I can think about where you want to use & is if the second operand has a side effect, for example (probably not the best example but you get the point):
public static void main(String[] args) {
int i = 1;
if (i == 0 & ++i != 2) {
}
System.out.println(i); //2
i = 1;
if (i == 0 && ++i != 2) {
}
System.out.println(i); //1
}
However, this looks like smelly code to me (in both cases).
The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.
A single & will run both sides regardless.
So, as a contrived example, you might have:
if (account.isAllowed() & logAccountAndCheckFlag(account))
// Do something
In that example, you might always want to log the fact that the owner of the account attempted to do something.
I don't think I have ever used a single & in commercial programming though.
Wikipedia has nicely described the Short Circuit Evaluation
Where do you prefer non short-circuit operators ?
From the same link:
Untested second condition leads to unperformed side effect
Code efficiency
Short-circuiting can lead to errors in branch prediction on modern
processors, and dramatically reduce performance (a notable example is
highly optimized ray with axis aligned box intersection code in ray
tracing)[clarification needed]. Some compilers can detect such cases
and emit faster code, but it is not always possible due to possible
violations of the C standard. Highly optimized code should use other
ways for doing this (like manual usage of assembly code)
If there are side effects that must happen, but that's a little ugly.
The bitwise AND (&) is mostly useful for just that - bitwise math.
Input validation is one possible case. You typically want to report all the errors in a form to the user in a single pass instead of stopping after the first one and forcing them to click submit repeatedly and only get a single error each time:
public boolean validateField(string userInput, string paramName) {
bool valid;
//do validation
if (valid) {
//updates UI to remove error indicator (if present)
reportValid(paramName);
} else {
//updates UI to indicate a problem (color change, error icon, etc)
reportInvalid(paramName);
}
}
public boolean validateAllInput(...) {
boolean valid = true;
valid = valid & validateField(userInput1, paramName1);
valid = valid & validateField(userInput2, paramName2);
valid = valid & validateField(userInput3, paramName3);
valid = valid & validateField(userInput4, paramName4);
valid = valid & validateField(userInput5, paramName5);
return valid;
}
public void onSubmit() {
if (validateAllInput(...)) {
//go to next page of wizard, update database, etc
processUserInput(userInput1, userInput2, ... );
}
}
public void onInput1Changed() {
validateField(input1.Text, paramName1);
}
public void onInput2Changed() {
validateField(input2.Text, paramName2);
}
...
Granted, you could trivially avoid the need for short circuit evaluation in validateAllInput() by refactoring the if (valid) { reportValid() ... logic outside of validateField(); but then you'd need to call the extracted code every time validateField() was called; at a minimum adding 10 extra lines for method calls. As always it's a case of which tradeoff's work best for you.
If the expression are trivial, you may get a micro-optimisation by using & or | in that you are preventing a branch. ie.
if(a && b) { }
if(!(a || b)) { }
is the same as
if (a) if (b) { }
if (!a) if (!b) { }
which has two places a branch can occur.
However using an unconditional & or |, there can be only one branch.
Whetehr this helps or not is highly dependant on what the code is doing.
If you use this, I sugegst commenting it to make it very clear why it has been done.
There isn't any specific use of single & but you can consider the following situation.
if (x > 0 & someMethod(...))
{
// code...
}
Consider that someMethod() is doing some operation which will modify instance variables or do something which will impact behavior later in processing.
So in this case if you use && operator and the first condition fails it will never go in someMethod(). In this case single & operator will suffice.
Because & is a bit-wise operator, you can do up to 32-checks in a single operation concurrently. This can become a significant speed gain for this very specific use cases. If you need to check a large number of conditions, and do it often and the cost of boxing/unboxing the conditions are amortized by the number of checks, or if you store your data on-disk and on-RAM in that format (it is more space efficient to store 32 conditions in a single bitmask), the & operator can give a huge speed benefit over a series of 32 individual &&. For example if you want to select all units that can move, is an infantry, has weapon upgrade, and is controlled by player 3, you can do:
int MASK = CAN_MOVE | INFANTRY | CAN_ATTACK | HAS_WEAPON_UPGRADE | PLAYER_3;
for (Unit u in allunits) {
if (u.mask & MASK == MASK) {
...;
}
}
See my other answers on a related question for more on the topic.
The only benefit I can think of is when you need to invoke a method or execute a code, no matter the first expression is evaluated to true or false:
public boolean update()
{
// do whatever you want here
return true;
}
// ...
if(x == y & update()){ /* ... */}
Although you can do this without &:
if(x == y){/* ... */}
update();
Short-circuiting can lead to errors in branch prediction on modern processors, and dramatically reduce performance (a notable example is highly optimized ray with axis aligned box intersection code in ray tracing)[clarification needed].
if ((one.option != two.option) && (one.side == two.side))
I need to check the followng Business Logic above
so i written this way
if((data[0].getData.value()!=data[1].getData.value())
&&(data[0].getAction().value()==data[1].getAction().value()))
Is this correct ??
Assuming data[0] in place of one
getData.value() in place of option shown in the top if condition .
I am concerned about the brackets inside the if condition
It's correct, but personally I wouldn't bother with the brackets in this particular case. I would, however, use more whitespace. I'd write that as:
if (data[0].getData.value() != data[1].getData.value()
&& data[0].getAction().value() == data[1].getAction().value())
If you really want the brackets, I'd write it as:
if ((data[0].getData.value() != data[1].getData.value())
&& (data[0].getAction().value() == data[1].getAction().value()))
I'd normally only include the brackets if I wanted to differentiate between, say,
if ((x && y) || z)
and
if (x && (y || z))
Of course, this is assuming that the values are ones which are appropriate to compare with == and !=. If they're strings or other objects, you should potentially be using equals instead.
Two general comments.
First, consider using tests for this kind of thing, specifically test driven development, where you write the test first, fail it and then only write enough of a test to pass it. Then there will be no mystery whether the code is correct.
This is an exercise that will help you learn that approach.
Second, based on that snippet, it looks like your code could use some refactoring to make the intention clear, for example by putting them into a method with a clear name (in your case probably two) that gets called there. TDD tends to result in that kind of clean code, as long as you take the time to refactor once your tests pass.
Your parentheses are correct.
Your if statement is valid but it is difficult to read. I'd recommend following the advice of others about white-space and assigning the values to variables to improve readability. Well written code shouldn't require comments, it should be self evident what data your working with!
I wrote some code that looks similar to the following:
String SKIP_FIRST = "foo";
String SKIP_SECOND = "foo/bar";
int skipFooBarIndex(String[] list){
int index;
if (list.length >= (index = 1) && list[0].equals(SKIP_FIRST) ||
list.length >= (index = 2) &&
(list[0] + "/" + list[1]).equals(SKIP_SECOND)){
return index;
}
return 0;
}
String[] myArray = "foo/bar/apples/peaches/cherries".split("/");
print(skipFooBarIndex(myArray);
This changes state inside of the if statement by assigning index. However, my coworkers disliked this very much.
Is this a harmful practice? Is there any reason to do it?
Yes. This clearly reduces readability. What's wrong with the following code?
int skipFooBarIndex(String[] list){
if(list.length >= 1 && list[0].equals(SKIP_FIRST))
return 1;
if(list.length >= 2 && (list[0] + "/" + list[1]).equals(SKIP_SECOND))
return 2;
return 0;
}
It's much easier to understand. In general, having side effects in expressions is discouraged as you'll be relying on the order of evaluation of subexpressions.
Assuming you count it as "clever" code, it's good to always remember Brian Kernighan's quote:
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
...However, my coworkers disliked this very much...
Yes, it is. Not just because you can code it like that, you have to.
Remember that that piece of code will eventually have to be maintained by someone ( that someone may be your self in 8 months )
Changing the state inside the if, make is harder to read and understand ( mostly because it is non common )
Quoting Martin Fowler:
Any fool can write code that a computer can understand. Good programmers write code that humans can understand
There's an excellent reason not to do it: it's makes your code really hard to understand and reason about.
The problem is that the code would generate multiple-WTFs in a code review session. Anything that makes people go "wait, what?" has got to go.
It's sadly easy enough to create bugs even in easy-to-read code. No reason to make it even easier.
Yes, side effects are hard to follow when reviewing code.
Regarding reasons to do it: No, there is no real reason to do it. I haven't yet stumbled upon an if statement that can't be rewritten without side effects without having any loss.
The only thing wrong with it is that it's unfamiliar and confusing to people who didn't write it, at least for a minute while they figure it out. I would probably write it like this to make it more readable:
if (list.length >= 1 && list[0].equals(SKIP_FIRST)) {
return 1;
}
if (list.length >= 2 && (list[0] + "/" + list[1]).equals(SKIP_SECOND)) {
return 2;
}
Borrowed from cppreference.com:
One important aspect of C++ that is related to operator precedence is the order of evaluation and the order of side effects in expressions. In some circumstances, the order in which things happen is not defined. For example, consider the following code:
float x = 1;
x = x / ++x;
The value of x is not guaranteed to be consistent across different compilers, because it is not clear whether the computer should evaluate the left or the right side of the division first. Depending on which side is evaluated first, x could take a different value.
Furthermore, while ++x evaluates to x+1, the side effect of actually storing that new value in x could happen at different times, resulting in different values for x.
The bottom line is that expressions like the one above are horribly ambiguous and should be avoided at all costs. When in doubt, break a single ambiguous expression into multiple expressions to ensure that the order of evaluation is correct.
Is this a harmful practice?
Absolutely yes. The code is hard to understand. It takes two or three reads for anyone but the author. Any code that is hard to understand and that can be rewritten in a simpler way that is easier to understand SHOULD be rewritten that way.
Your colleagues are absolutely right.
Is there any reason to do it?
The only possible reason for doing something like that is that you have extensively profiled the application and found this part of code to be a significant bottleneck. Then you have implemented the abomination above, rerun the profiler, and found that it REALLY improves the performance.
Well, I spent some time reading the above without realising what was going on. So I would definitely suggest that it's not ideal. I wouldn't really ever expect the if() statement itself to change state.
I wouldn't recommend an if condition having side-effects without a very good reason. For me, this particular example took several looks to figure out what was going on. There may be a case where it isn't so bad, although I certainly can't think of one.
Ideally, each piece of code should do one thing. Making it do more than one thing is potentially confusing, and confusing is exactly what you don't want in your code.
The code in the condition of an if statement is supposed to generate a boolean value. Tasking it with assigning a value is making it do two things, which is generally bad.
Moreover, people expect conditions to be just conditions, and they often glance over them when they're getting an impression of what the code is doing. They don't carefully parse everything until they decide they need to.
Stick that in code I'm reviewing and I'll flag it as a defect.
You can also get ternary to avoid multiple returns:
int skipFooBarIndex(String[] list) {
return (list.length > 0 && list[0].equals(SKIP_FIRST)) ? 1 :
((list.length > 1 && (list[0] + "/" + list[1]).equals(SKIP_SECOND)) ? 2 : 0);
}
Though this example is less readable.
Speaking as someone who does a lot of maintenance programming: if I came across this I would curse you, weep and then change it.
Code like this is a nightmare - it screams one of two things
I'm new here and I need help doing the right thing.
I think I am very clever because I have saved lines of code or I have fooled the compiler and made it quicker. Its not clever, its not optimal and its not funny
;)
In C it's fairly common to change state inside if statements. Generally speaking, I find that there are a few unwritten rules on where this is acceptable, for example:
You are reading into a variable and checking the result:
int a;
...
if ((a = getchar()) == 'q') { ... }
Incrementing a value and checking the result:
int *a = (int *)0xdeadbeef;
...
if (5 == *(a++)) { ... }
And when it is not acceptable:
You are assigning a constant to a variable:
int a;
...
if (a = 5) { ... } // this is almost always unintentional
Mixing and matching pre- and post-increment, and short-circuiting:
int a = 0, b;
...
if (b || a++) { ... } // BAD!
For some reason the font for sections I'm trying to mark as code is not fixed-width on SO, but in a fixed width font there are situations where assignment inside if expressions is both sensible and clear.