I am writing a code and am following all instructions given to me. All the codes and methods look fine when I run the program but the equal method! Based on the instructions, I am supposed to get false when the tested asks if point (a, b)---(c, d) is equals to (e, f)---(g, h), but I get true. Can Anyone give me an idea where I am doing wrong?
Thank you in advance!
/**
* The equals method should return true if the given object is equal to the
* the Object passed in. Note that this method receives an Object; there is
* a particular way that this method should be implemented (see notes from class).
*
* Notice that two Segments are equal even if their endpoints are swapped
* i.e.: (1, 2)---(3, 4) == (3, 4)---(1, 2)
*/
public boolean equals(Object obj) {
//if (obj instanceof Segment) {
//Segment other = (Segment) obj;
//return p1 == other.getP1() && p2 == other.getP2();
//}
//else {
//throw new IllegalArgumentException("undefined");
//}
if(obj == null)
return false;
if(this == obj)
return true;
if(!(obj instanceof Segment))
return false;
else if(obj.getClass() != this.getClass()){
return false;
}
else
{
Segment S = (Segment)obj;
if(this.getP1() == S.getP1() &&
this.getP2() == S.getP2());
return true;
//else if(obj.getP1() != this.getP1() &&
// obj.getP2() != this.getP2());
// return false;
}
}
if(this.getP1() == S.getP1() &&
this.getP2() == S.getP2());
^
Take out this semicolon.
Then you will also need to return a value if the if statement isn't met.
Edit
Currently your if statement is serving no purpose. Take out the semicolon so that the following return statement is qualified by the if. Then after that add a return false that will be applied if the if statement isn't met.
Like this:
if (this.getP1()==S.getP1() && this.getP2()==S.getP2()) {
return true;
}
return false;
Or, put more simply:
return (this.getP1()==S.getP1() && this.getP2()==S.getP2());
Related
I have written a method that searches a tree to test if any integers are negative.
But I am struggling to get the right Boolean value returned. Any pointers as to where I am going wrong?
What I want to achieve is that as soon as the condition statement is met a false is returned but unfortunately my code is always returning a true
static boolean allE(Tree<Integer> x) {
if (x.isEmpty()) return true;
else {
if (x.getValue()%2 != 0) return false;
}
allE(x.getLeft());
allE(x.getRight());
return true;
}
When you recurse on allE you need to consider the result of that recursion. Easiest fix I see, change
allE(x.getLeft());
allE(x.getRight());
return true;
to
return allE(x.getLeft()) && allE(x.getRight());
Although, I think it makes more sense to write the algorithm such that you recurse on even explicitly. And allE saves three letters compared to allEven (please use meaningful names for methods and variables). Something like,
static boolean allEven(Tree<Integer> node) {
if (node.isEmpty()) {
return true;
} else if (node.getValue() % 2 == 0) {
return allEven(node.getLeft()) && allEven(node.getRight());
}
return false;
}
You're not using the results of your recursive tests properly.
It should be:
if (x.isEmpty()) {
return true;
}
boolean thisNodeEven = x.getValue() % 2 == 0;
return thisNodeEven && allE(x.getLeft()) && allE(x.getRight());
I suppose you need to evaluate the return-value of the recursive calls:
static boolean allE(Tree<Integer> x)
{
if (x.isEmpty())
return true;
else {
if (x.getValue()%2 != 0) return false;
}
if(!allE(x.getLeft()) || !allE(x.getRight()))
return false;
return true;
}
I am iterating over two collections and check if both collections contain
the same elements. I can't use Java 8.
edit 1 year after:
I created the method in the question to check if two Collections contain the same elements, without thinking about the fact that I am passing two Collection implementations into the method.
But Collection does not determine how elements are sorted. And I am iterating over the collections. Thus, some implementation of Collection could save elements in random order, while containing the same elements.
Both collections contain elements that are comparable and the content
is defined as equal, if all elements return a x.compareTo(y) with 0.
Two values are defined as different, if one of them is null, but not the other.
I want to find an elegant way to compare on nullity and prevent
a null check on the final compareTo().
My current implementation:
public static <T extends Comparable<T>> boolean isSame(#Nullable Collection<T> a, #Nullable Collection<T> b) {
if (a == null || b == null) {
return (a == null && b == null);
}
if (a.size() != b.size()) {
return false;
}
Iterator<T> aIt = a.iterator();
Iterator<T> bIt = b.iterator();
while (aIt.hasNext()) {
T aValue = aIt.next();
T bValue = bIt.next();
if (aValue == null || bValue == null) {
if (aValue == null ^ bValue == null) {
return false;
}
//both null, don't compare, continue looping...
} else if (aValue.compareTo(bValue) != 0) {
return false;
}
}
return true;
}
I want to continue the while loop, if both values are null, because that is
defined as equal.
But I am struggling with this part:
if (aValue == null || bValue == null) {
if (aValue == null ^ bValue == null) {
return false;
}
}
Question:
Is there a more elegant and readable way to compare on nullity, do a further compare if both are not null, return false if only one is null, and continue the loop, if both values are null?
The sequence as follows should work well:
if(aValue == null && bValue == null) continue; // both null; continue
if(aValue == null || bValue == null) return false; // any null; return false
if(aValue.compareTo(bValue) != 0) { // both non-null; compare
return false;
}
In Java8, you can build a Comparator that would replace comparison sequence at cost of creating an extra object (you will need to decide if you care about that):
Comparator<T> cmp = Comparator.nullsLast(Comparator.naturalOrder());
The compararor will take care of null comparison for you (since you assume that two nulls are equal):
while (aIt.hasNext()) {
T aValue = aIt.next();
T bValue = bIt.next();
if (cmp.compare(aValue, bValue) != 0) {
return false;
}
}
This is what I have to do. The Binary Search Tree ADT is extended to include a bool ean method si m i l ar Trees that receives references to two binary trees and determines whether the shapes of the trees are the same. (The nodes do not have to contain the same values, but each node must have the same number of children.) I have code to show what I have.
public static <T> boolean similarTrees(BSTNode<T> a, BSTNode<T> b) {
// check for reference equality and nulls
if (a == b) return true; // note this picks up case of two nulls
if (a == null) return false;
if (b == null) return false;
// check for data inequality
if (a.data != b.data) {
if ((a.data == null) || (b.data == null)) return false;
if (!(a.data.equals(b.data))) return false;
}
// recursively check branches
if (!similarTrees(a.left, b.left)) return false;
if (!similarTrees(a.right, b.right)) return false;
// we've eliminated all possibilities for non-equality, so trees must be equal
return true;
}
In an example in class we were given this method as part of a bigger problem:
public boolean isWinner()
{
return ((points == 4) || (score == 4));
}
My impression of boolean type methods was that they HAVE to return true/false like "return true;" In this example there is no where indicating whether it is returning true/false so if points == 4 does it return true? and if score ==4 does it return false? or is it if either are true then the entire return statement is true?
If either points == 4 or score == 4 is true, the whole thing will be true. All boolean expressions evaluate down to either true or false.
This expression:
return ((points == 4) || (score == 4));
Will either return true or false.
|| is the OR operator. Which for two expressions has the following truth table:
T T = T
T F = T
F T = T
F F = F
So if both points and score are false then the function will return false. Otherwise it will return true.
return ((points == 4) || (score == 4));
Execution of above will result in return true or return false
From specification.
The value produced by the == operator is true if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is false.
also read about || operation in specification I hope that will clear your doubts
This
return (points == 4) || (score == 4);
is the same as
boolean ret = (points == 4) || (score == 4);
return ret;
which is the same as
if (points == 4) return true;
if (score == 4) return true;
return false;
You should take a look at the Java truth tables for || and &&. This will help give you an understanding of boolean results.
As your question stands, it will return true if either of those statements are true and false if they are both false.
There is only one exception in that code.
In the case that points/score are Integer referencing null, would cause an exception.
public class Snippet {
private Integer points;
private Integer score;
public boolean isWinner() {
return ((points == 4) || (score == 4));
}
public static void main(String[] args) {
System.out.println(new Snippet().isWinner());
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at snippet.Snippet.isWinner(Snippet.java:8)
at snippet.Snippet.main(Snippet.java:13)
public static boolean isCompatibleForMultiplcation(final Matrix a, final Matrix b)
{
if (a == null)
{
throw new IllegalArgumentException("a cannot be null");
}
if (b == null)
{
throw new IllegalArgumentException("b cannot be null");
}
if(!(a.getNumberofColumns()== b.getNumberOfRows()))
{
return false;
}
else
{
return true;
}
}
I am getting a 'Conditional Logic can be removed argument in checkstyle for the following method. I cannot seem to figure out why... Can someone give me a pointer?
It is complaining about this part right here :
if(a.getNumberofColumns() != b.getNumberOfRows())
{
return false;
}
else
{
return true;
}
Whenever you see yourself writing code like this you can easily replace it with a single line by just returning the condition from the if statement:
return a.getNumberofColumns() == b.getNumberOfRows();
This statement will return true if the the number of columns for a and rows for b are equal, and false otherwise.