Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have the following boolean method in Java, but I can't understand its return statement because it uses a ternary operation. Can anyone rewrite it to an if/else statement so that I can better understand what the ternary operation is doing?
public boolean collidesWith(Rectangle object){
return (isDestroyed)? false:hitbox.intersects(object);
}
The ternary operator is a short-hand for writing an if-else statement. Its general for is
<boolean condition to evaluate> ?
<return value if condition is true - i.e., the "if" branch > :
<return value is condition is false - i.e., the "else" branch>
So, if you unwrap the method you showed, you'd get:
public boolean collidesWith(Rectangle object){
if (isDestroyed) {
return false;
} else {
return hitbox.intersects(object);
}
}
Firstly, here is how I would write the method you posted (adding whitespace):
public boolean collidesWith(Rectangle object) {
return isDestroyed ? false : hitbox.intersects(object);
}
Here is the if-else you're looking for:
public boolean collidesWith(Rectangle object) {
if (isDestroyed) {
return false;
}
else {
return hitbox.intersects(object);
}
}
..or a bit simplified:
public boolean collidesWith(Rectangle object) {
if (isDestroyed)
return false;
return hitbox.intersects(object);
}
You may also make the ternary operator look a bit like an if-else:
public boolean collidesWith(Rectangle object) {
return isDestroyed ?
false :
hitbox.intersects(object);
}
public boolean collidesWith(Rectangle object){
if(isDestroyed)
return false;
else
return hitbox.intersects(object);
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I was practicing linked-list problem: search element using recursion in Java and was just curious to know which approach is better?
A:
protected boolean searchElement(Node current, int element){
boolean res = false;
if(current != null){
if(current.getData() == elem) res = true;
else function(current.getNext(),elem);
}
else res = false;
return res;
}
B:
protected boolean searchElement(Node current, int elem){
if(current != null){
if(current.getData() == elem) return true;
else search(current.getNext(), elem);
}
return false;
}
Unless there's specific Java-hackish bytecode injection optimization reasons for using end-recursion/tail-call strategy in recursive functions, I would even go for this (fail-fast-fail-early):
protected boolean function(arguments){
if(!condition_1) return false;
if(condition_2) return true;
return function(arguments);
}
BTW you may have an error in your pseudo code:
In both A and B, the handling of
else function(arguments);
looks inconsequential. It will run the function, but both implementations will return false, no matter what function() does (unless it throws an uncaught exception/throwable). This indicates either
a mistake in programming,
or some side-effects (changing exterior state variables such as static or member variables), which recursive functions rather should NOT do
If this is only a mistake in programming/design, I suggest you always translate pseudocode into real code. This way the compiler will usually tell you such things, make them more evident. Amp up your clean code / code smell warning settings.
Oh, and another note to consider: you can always replace recursive functions with a loop and some variables/lists, which usually drastically increases speed (no creation and release of stack frames when running) but often reduces readability (multiple variables to mess up, instead of cleanly assigned parameters).
For your example, as the impact of the call to function() is unclear, I cannot present you a meaningful example here.
I prefer handling the special cases first, then the recursion (as far as feasible).
This in a code style with several returns - which many do not find good style.
But it prevents nested conditions and else.
protected boolean searchElement(Node current, int element) {
if (current == null) {
return false;
}
if (current.getData() == elem) {
return true;
}
return search(current.getNext(), elem);
}
Case: terminating condition on null node.
Case: found.
Recursion, here last, so called tail recursion.
Tail recursion can be easily transformed to iteration.
protected boolean searchElement(Node current, int element) {
while (current != null) {
if (current.getData() == elem) {
return true;
}
current = current.getNext();
}
return false;
}
I have a use-case where I want to return boolean value from the function
private boolean checkStatus(String param) {
return param != null ? randomBool() : true;
}
private boolean randomBool() {
// return true or false on the basis of some condition
}
I am getting complaint issue over true statement. What could be the other way to achieve the same?
Sonar issue: Redundant Boolean literals should be removed from expressions to improve readability.
Just change your code to the next:
param == null || randomBool()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to understand the basics of for loops and how they work with booleans. There is a simple few lines of code that I wrote and I don't quite understand why the output is what it is.
public class notes {
public static void main(String[] args) {
boolean[] test = {false, false, true};
if (test[0] = false) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
I would assume that because the boolean value at index 0 in the test array is false, then this if statement should also print yes. However, it prints no. Why is this?
Try it like this. Since conditionals result in a true or false condition you can just use the boolean by itself. Since you want it to print yes when false, you need to make it true so the conditional will succeed. So invert the condition by prefixing a bang ! (aka the NOT operator).
public class notes {
public static void main(String[] args) {
boolean[] test = {false, false, true};
// if false do it.
if(!test[0]) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
You are assigning false to the first element of the array, which evaluates to false and causes the else branch to be executed instead. You need to use == for comparison and in the case of booleans, you can simply use the logical not operator (!) to check if it is false. It is always redundant to compare boolean values, as the result of comparison is a boolean.
if(!test[0]) {
System.out.println("yes");
} else {
System.out.println("no");
}
You are using an assignment operator =, instead of using a comparison operator ==, hence you don't compare, but rather assign a false value to the index 0 of your array and the same false is then evaluated as a boolean value; therefore, else block executes.
Try this instead:
public class notes {
public static void main(String[] args) {
boolean[] test = {false, false, true};
if(test[0] == false) { //you had a mistake here.
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
Note, that you can alternatively negate boolean expression with ! unary operator, like !booleanValue. In your case it would look like !test[0].
Have a look at operators in Java.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Writing this code, I'm getting 'unreachable statement' error when I try to compile, any time I try to reach a[x] in the recursive method.
public class recursion
{
public static boolean match (int [] a, int [] pattern)
{
if(pattern.length==0)
return true;
boolean x;
x=match(a,pattern,0,0);
if(x==true)
return true;
return false;
}
public static boolean match (int [] a, int [] pattern,int aCounter,int ptCounter)
{
int count=0;
int x=aCounter;
if(x==a.length);
{
if(count==pattern.length)
return true;
else return false;
}
if(a[x]>100)
{
count=0;
return match(a,pattern,aCounter+1,0);
}
else if(((pattern[ptCounter]==1)||(pattern[ptCounter]==0))&&((a[x]>-10)&&(a[x]<10)))
{
count++;
return match(a,pattern,aCounter+1,ptCounter+1);
}
else if(((pattern[ptCounter]==2)||(pattern[ptCounter]==0))&&(((a[x]<-10)&&(a[x]>-100))||((a[x]>9)&&(a[x]<100))))
{
count++;
return match(a,pattern,aCounter+1,ptCounter+1);
}
}
}
Would appreciate input regarding this issue and also about the calling of recursive method. Thank you!
Your problem is an unnecessary ; :
if(x==a.length); // here
{
if(count==pattern.length)
return true;
else return false;
}
This ; closes the if statement, so the following bock is always executed (and returns true or false), and the code after that block becomes unreachable.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to override equals on a custom object and want to check whether the current object is equal to the one passed in the parameter by Id (getId). How can I do that? Thanks
It's very difficult to give you an answer with only the information you've provided. But you want something roughly like this:
#Override
public boolean equals(Object o) {
if (! (o instanceof MyClass)) return false;
return id == ((MyClass)o).getId();
}
Where id is your data field (presumably an int) and MyClass is the name of your class.
As a note: If you override equals, it is strongly encouraged that you also override hashCode. If id is indeed an integer, then you might consider having hashCode just return id.
You need to check the type and "nullness" of the incoming object. You should also check whether or not this.id is null just to be thorough. You also are probably going to want to override Object.hashCode() as well so that Sets and Maps work like you want.
#Override
public boolean equals(Object obj) {
if ((obj == null) || (!getClass().isAssignableFrom(obj.getClass()))) {
return false;
}
if (this.id == null) {
return false;
} else {
return this.id.equals((ClassName)obj.getId());
}
}
#Override
public int hashCode() {
return this.id.hashCode();
}